JavaScript's self and this use summary

One, self
  is very simple. We know that when opening any web page, the browser will first create a window. This window is a window object, and it is also the global environment object and global scope object to which js runs. self refers to the window itself, and the object it returns is exactly the same as the window object. Because of this, the common methods and functions of the window object can use self instead of window. For example, a common spelling such as "self.close();", put it in the <a> tag: "<a href="javascript:self.close();">close the window</a>" , click the "Close Window" link to close the current page.
2. This keyword
  Before talking about this, look at the following code:
<body>
<script type="text/javascript">
function thisTest()
{
this.textValue = 'this's dom test';
this.element= document .createElement('span');
this.element.innerHTML = this.textValue;
this.element.style.color = "blue";
this.element.style.cursor = "pointer";
this.element.attachEvent('onclick ', this.ToString);
}

thisTest.prototype.RenderDom = function()
{
document.body.appendChild(this.element);
}

thisTest.prototype.ToString = function()
{
alert("Click me: "+this.textValue);
};
var test= new thisTest();
test.RenderDom();
//test.ToString();
</ The original purpose of script>
</body>
is to add a span element to the body. For this span element, its font color, the mouse style hovering above it, and the click trigger event are specified. The problem is with its click event ("click me: undefined" pops up). Some people may say that you are stupid. Isn't writing so much sb code just to realize the following stuff?
<span style='cursor:pointer;color:blue;' onclick="alert(this.innerHTML)">this's dom test</span>
1. What does this mean?
The familiar c# has this keyword, and its main function is to refer to the current object instance (parameter passing and indexers both use this). In javascript, this usually refers to the function we are executing itself, or to the object (runtime) to which the function belongs.
2. Common usage
(1), use directly in the dom element
<script type="text/javascript">
function thisTest(){
alert(this.value);

</script>
<input id="btnTest" type="button" value="Submit" onclick="thisTest()" />
Analysis: The onclick event directly calls the thisTest function, and the program will pop up undefined. Because the thisTest function is defined in the window object,
the owner (scope) of thisTest is window, and the this of thisTest is also window. The window does not have a value attribute, so an error is reported.
b. The correct way
<input id="btnTest" type="button" value="submit" />
<script type="text/javascript">
function thisTest(){
alert(this.value);
}
document.getElementById ("btnTest").onclick=thisTest; //Register a function for the button's onclick event
</script>
Analysis: In the previous example, the thisTest function is defined in the global scope (here is the window object), so this refers to the current window object. In the form of document.getElementById("btnTest").onclick=thisTest;, the onclick property of btnTest is actually set as a copy of thisTest function. In the function scope of the onclick property of btnTest, this is owned by btnTest, and this It also points to btnTest. In fact, if there are multiple dom elements to register the event, we can use different dom element ids to achieve it in the following way:
document.getElementById("domID").onclick=thisTest; //Register a function for the button's onclick event .
Because multiple different HTML elements create different function copies, the owner of each copy is the corresponding HTML element, and the respective this also points to their owner, which will not cause confusion.
In order to verify the above statement, let's improve the code and let the buttons directly pop up their corresponding trigger functions:
<input id="btnTest1" type="button" value="Submit 1" onclick="thisTest()" />
<input id ="btnTest2" type="button" value="Submit 2" />

<script type="text/javascript">
function thisTest(){
this.value="Submitting";
}
var btn=document.getElementById("btnTest1");
alert(btn.onclick); //first button Function
var btnOther=document.getElementById("btnTest2");
btnOther.onclick=thisTest;
alert(btnOther.onclick); //The second button function
</script>
The pop-up result is:
//The first button
function onclick(){
thisTest()
}
//The second button
function thisTest(){
this.value="Submitting";
}
You must understand more thoroughly from the above results.
By the way, every time a new copy of a function is created, the program allocates a certain amount of memory for this copy of the function. In practical applications, most functions are not necessarily called, so this part of the memory is wasted. So we usually write like this:
<input id="btnTest1" type="button" value="Submit 1"
<input id="btnTest2" type="button" value="Submit 2" onclick="thisTest(this)" />
<input id="btnTest3" type="button" value="Submit 3" onclick="thisTest (this)" />
<input id="btnTest4" type="button" value="Submit 4" onclick="thisTest(this)" />
<script type="text/javascript">
function thisTest(obj){
alert(obj.value);
}
</script>
This is because we use the function reference method, the program will only allocate memory to the body of the function, and the reference will only allocate pointers. Write a function like this, and assign a (pointer) reference to it where it is called, which is much more efficient. Of course, if you feel that registering events in this way is not compatible with multiple browsers, you can write the following general script for registering events:
//js events add EventUtil.addEvent(dom element, event name, function name triggered by the event) Remove EventUtil. removeEvent(dom element, event name, function name triggered by the event)
var EventUtil = new eventManager();



oEventType: event name (eg: click, if it is an ie browser, automatically convert click to onclick); ** oFunc: the name of the function triggered by the event
this.addEvent = function(oDomElement, oEventType, oFunc) {
//ie
if ( oDomElement.attachEvent) {
oDomElement.attachEvent("on" + oEventType, oFunc);
}
//ff,opera,safari etc.
else if (oDomElement.addEventListener) {
oDomElement.addEventListener(oEventType, oFunc, false);
}
//other
else {
oDomElement["on" + oEventType] = oFunc;
}
}
this.removeEvent = function(oDomElement, oEventType, oFunc) {
//ie
if (oDomElement.detachEvent) {
oDomElement.detachEvent("on" + oEventType, oFunc) ;
}
//ff,opera,safari etc.
else if (oDomElement.removeEventListener) {
oDomElement.removeEventListener(oEventType, oFunc, false);
}
//Other
else {
oDomElement["on" + oEventType] = null;
}
}
}
As the comment says, to register the dom element For events, use EventUtil.addEvent(dom element, event name, event-triggered function name). When removing, you can write: EventUtil.removeEvent(dom element, event name, event-triggered function name). This is off-topic, don't talk about it.
(3) The use of this keyword in class definitions is
actually quite common. See the example:
function thisTest()
{
var tmpName = 'jeff wong';
this.userName= 'jeff wong';
}
var test= new thisTest() ;
alert(test.userName==test.tmpName);//false
alert(test.userName); //jeff wong
alert(test.tmpName); //undefinedAnalyze
the result, in fact, this and c# here are akin.
(4), add a prototype method to the script object
The premise of understanding this is that you must understand the concept of prototype in js (speaking here, kao, I really need to face the wall): The prototype property of an object in js is used to return a reference to the prototype of the object type. All js internal objects have a read-only prototype property that can dynamically add functionality (properties and methods) to their prototype,
but the object cannot be assigned a different prototype. But user-defined objects can be assigned new prototypes. Look at a simple example:
//js's internal object String, dynamically add functions (properties and methods) to its prototype
//remove the blank characters at both ends of the string
String.prototype.Trim = function() {
return this.replace( /(^\s+)|(\s+$)/g, "");
}
function thisTest()
{
var tmpName = 'jeff wong';
this.userName= ' jeff wong ';
}
//for user-defined objects Add prototype method
thisTest.prototype.ToString = function()
{
alert(this.userName); //jeff wong ( with space )
alert(this.userName.Trim()); //jeff wong ( without space )
//alert (tmpName); //Script error, tmpName is not defined
}
var test= new thisTest();
test.ToString(); //call prototype's ToString()
function myTest(){
this.userName= ' test ';
}
var test1=new myTest();
//test1.ToString( ); //Calling the ToString() method is temporarily not supported here.//The
user-defined object is assigned a new prototype
myTest.prototype = new thisTest(); test1.ToString(); //The test result
of calling the prototype's ToString()
It is shown that this here refers to the instance of the class to which the prototype (method or property) is added, which is basically similar to the definition in (3).
(5), use the this keyword in the inner function of the function.
If you understand scope and closure, the problem will be solved easily. See the most typical example:
function thisTest()
{
this.userName= 'outer userName';
function innerThisTest(){
var userName="inner userName";
alert(userName); //inner userName
alert(this.userName); / /outer userName
}
return innerThisTest;
}
thisTest()();
Analysis: thisTest() calls the innerThisTest function to form a closure. When innerThisTest is executed, innerUserName pops up for the first time, because there is a variable called userName in the scope of innerThisTest function, so the specified value of the variable in the current scope is directly popped up; the second time outer userName pops up is because there is no userName property in innerThisTest scope (example this.userName in the example), so it looks for the userName property in the upper-level scope, and this time it is found in thisTest (this.userName='outer userName'; in the example), so the corresponding value pops up.
(6) Specify a specific this designation through the function's call and apply functions
, this may cause a situation of "you have me, I have you", if you don't want to confuse yourself, just get to know it That's it. Changing this specified object is also a very bad thing for code maintenance. Post the example code from the old article and end it:
function myFuncOne() {
this.p = "myFuncOne-";
this.A = function(arg) {
alert(this.p + arg);
}
}
function myFuncTwo() {
this .p = "myFuncTwo-";
this.B = function(arg) {
alert(this.p + arg);
}
}
function test() {
var obj1 = new myFuncOne();
var obj2 = new myFuncTwo();
obj1.A("testA"); //display myFuncOne-testA
obj2.B("testB"); //display myFuncTwo-testB
obj1.A. apply(obj2, ["testA"]); //display myFuncTwo-testA, where [testA"] is an array with only one element
obj2.B.apply(obj1, ["testB"]); //display myFuncOne- testB, where [testB"] is an array with only one element
obj1.A.call(obj2, "testA"); //display myFuncTwo-testA
obj2.B.call(obj1, "testB"); //display myFuncOne -testB
}
Summary: At this point, have you suddenly understood the problem of undefined popping up in the span in the opening paragraph? If you are still ignorant, give a dispensable hint: Does the current span element have a textValue attribute? ?
Three, void
1, define
void in javascript is an operator, the operator specifies to calculate an expression but does not return a value.
2. The syntax of
the void operator is as follows:
(1). javascript:void (expression)
(2). javascript:void expression
Note: expression is a js-standard expression to be evaluated. The parentheses around the expression are optional, but by writing it you can tell at a glance that the parentheses are an expression (this is the same as the expression syntax after typeof).
3. Example code
function voidTest() {
void (alert("it is a void test")); //Execute function
var oTestNum = 1;
void (oTestNum++); //Integer self-increment
alert(oTestNum);
oTestNum = 1 ;
void (oTestNum += "void test"); //Integer plus string
alert(oTestNum);
}
voidTest();
4. Use void(0) under a element
(1) Applicable situation
In web pages, we often When you see that the a tag in html does not need it to navigate to a certain page, the writing method of the href attribute setting:
<a href="#">link1</a>
<a href="javascript:void(0);"> link2</a>
Note: The first way of writing "#" (in fact, # can be multiple, usually 1), when the link where the a element is located is below one screen of the browser, it will cause the page to scroll back to the top; so when we If you need the a tag not to navigate to other pages, and you don't need to roll back the position of the web page, void(0) will be used.
(2) The weird problem caused by void(0) under ie6
There are many discussions on the Internet ."The summary is very representative and will not be repeated here.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325678000&siteId=291194637