w3resource

JavaScript: this Operator

Description

The this operator is used to refer the current object. In general, this refers to the calling object in a method.

Syntax

this.propertyName

Parameter

propertyName: The name of the property.

Example:

In the following web document, this operator is used as internal reference property of the form instances.

HTML Code

<!doctype html>
<head>
<meta charset="utf-8">
<title>JavaScript this operator example with DOM
</title>
<meta name="description" content="This document contains an
example of JavaScript this operator"/>
</head>
<body>
<form name="myform" action="#">
<input type="text" value="Text Here" name="text1" />
<input type= "submit" value="Submit" name="mysubmit" onclick=
"formdetails(this.form)" />
</form>
<script src="javascript-this-operator-example1.js">
</script>
</body>
</html>

JS Code

function formdetails(form)
{
var newParagraph = document.createElement("p"); //creates a new
paragraph element var newText = document.createTextNode("The name
of the form is: "+form.name); //creates text along with ouput to be
displayed 
newParagraph.appendChild(newText); //created text is appended to the
paragraph element created document.body.appendChild(newParagraph);
// created paragraph and text along with output is appended to the
document body


var newParagraph1 = document.createElement("p"); //creates a new
paragraph element var newText1 = document.createTextNode("The
deault value of text box is: "+form.text1.value); //creates text
along with ouput to be displayed newParagraph1.appendChild
(newText1); //created text is appended to the paragraph element
created document.body.appendChild(newParagraph1);
// created paragraph and text along with output is appended to the
document body

var newParagraph2 = document.createElement("p"); //creates a new
paragraph element var newText2 = document.createTextNode("The name
of the submit button box is: "+form.mysubmit.name); //creates text
along with ouput to be displayed newParagraph2.appendChild(newText2);
//created text is appended to the paragraph element created
document.body.appendChild(newParagraph2);
// created paragraph and text along with output is appended to the
document body

var newParagraph3 = document.createElement("p"); //creates a new
paragraph element var newText3 = document.createTextNode("The deault
value of submit button is: "+form.mysubmit.value); //creates text
along with ouput to be displayed newParagraph3.appendChild(newText3);
//created text is appended to the paragraph element created
document.body.appendChild(newParagraph3);
// created paragraph and text along with output is appended to the
document body
}

View the example in the browser

See also

Conditional Operator
comma
delete
function
in
instanceof
new
typeof
void

Previous: JavaScript: new Operator
Next: JavaScript: typeof operator

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.