Javascript This keyword uses profiling _javascript tips

Source: Internet
Author: User
Tags prototype definition

About JS in this keyword article has been a lot of, I have seen several, I wrote this article is the purpose of the analysis from the example of this work principle, I hope to help.

First, the basic:

Copy Code code as follows:

function dosomething () {
alert (this.id);
}
Alert (window.dosomething)//proves that dosomething belongs to window
DoSomething ();//undefined
Window.onload = function () {
document.getElementById ("Div2"). onclick = Dosomething;//div2
document.getElementById ("Div3"). onclick = function () {dosomething ();} Undefined
}

1, for dosomething this function:
Copy Code code as follows:

function dosomething () {
alert (this.id);
}

This function is a global function, which actually belongs to the window (which can be accessed through window.dosomething), and if it is called directly, then "This always refers to the" owner "the function We ' re executing ', then this is window in the function, but window does not have ID attribute, so show "undefined";

2, in the HTML element this call
Copy Code code as follows:

<div id= "Div1" onclick= "dosomething ();" >div1</div>


"Undefined" is also displayed, which is equivalent to the following code:
Copy Code code as follows:

document.getElementById ("Div1"). onclick = function () {dosomething ();}

When clicked Div1, call belongs to Window dosomething function, so also show "undefined";

3, through JS to bind the event, after Div2 loading:
Copy Code code as follows:

document.getElementById ("Div2"). onclick = dosomething;

When clicked Div2, display "Div2", because in give the div2 the onclick assignment, is the dosomething copy once, then the copy this function belongs to the DIV2, has no relation with the dosomething which belongs to the window. When you click Div2, it triggers the dosomething that belongs to Div2, where this refers to Div2.

Ii. Attachevent and AddEventListener

Attachevent is a method of binding events in IE that copies the corresponding function to the global (that is, the response function's owner window), but in the DOM standard, the owner of the response function that is copied when addeventlistener the bound event is the object that the event is bound to
Copy Code code as follows:

function dosomething () {
alert (this.id);
Alert (this = = window);
}
Window.onload = function () {
var div1 = document.getElementById ("Div1");
if (div1.attachevent) {
Div1.attachevent ("onclick", dosomething);
Document.body.appendChild (document.createTextNode ("attachevent"));
}else if (div1.addeventlistener) {
Div1.addeventlistener ("click", Dosomething,false);
Document.body.appendChild (document.createTextNode ("AddEventListener"));
}else{
Div.onclick = dosomething;
}
}


for function dosomething
Copy Code code as follows:

function dosomething () {
alert (this.id);
Alert (this = = window);
}

1, using attachevent binding to the Div1 click event, dosometing will be copied to window, then dosomething inside of this refers to window, click Div1 will display "undefined" and " True

2, the use of AddEventListener binding Div1 Click event, then will dosomething copy, the function after this copy belongs to Div1, so click Div1 will show "Div1" and "false"

Note: http://www.quirksmode.org/js/this.html that attachevent just use a reference to the function, look at the following code:
Copy Code code as follows:

var obj = new Object ();
Obj.color = "BLACK";
Obj.showcolor = function () {
alert (This.color);
Alert (this = = window);
}
Obj.showcolor ();

var div1 = document.getElementById ("Div1");
Div1.attachevent ("onclick", Obj.showcolor);

When you click Div1, you will see "Undefined" and "true". If attachevent is merely referring to Obj.showcolor, then this should be referred to as obj, but in fact this here refers to window, so I think this is not a reference but a copy to the global.

Third, about the object pseudo inheritance Way

1, the difference between new and not new

For the following function
Copy Code code as follows:

function ClassA (scolor) {
This.color = Scolor;
This.saycolor = function () {
alert (This.color);
}
}

Is this a class or a function? Whatever you do!

If you think this is a function, then we can call it this way:

ClassA ("Red");
"Red" is an argument passed, and this in ClassA refers to the window of course, so now the window has the color attribute and the Saycolor method, and the color has the value "red".

This is called Saycolor or window.saycolor can display "red";

Window.saycolor ();


If you think this is a class, then we should use it this way:

var obj = new ClassA ("Red");
The new keyword appears to add a lot of content to the above code: first, create an instance of object, then point to this object created in ClassA, and return this object, so the object returned is assigned to obj. So we can say that this point is Obj,obj has the color property and the Saycolor method, and the Color property value is "red."

2, the function of the Owener
Copy Code code as follows:

function Showid () {
alert (this.id);
}
Window.onload = function () {
var div1 = document.getElementById ("Div1");
Div1.onclick = Showid;
Div1.show = Showid;
Div1.show ();

var obj = new Object ();
obj.id = "obj";
Obj.show = Showid;
Obj.show ();
}

We can assign the Showid function to the click event, or to any property of any object, which is also copied showid this method, So when we call the Div1.show method, this is pointing to Div1, and when we call Obj.show, this points to obj.

3. The principle of object posing

The following code is an inheritance that is implemented through an object impersonation method
Copy Code code as follows:

function ClassA (scolor) {
This.color = Scolor;
This.saycolor = function () {
alert (This.color);
}
}

function ClassB (scolor,sname) {
This.newmethod = ClassA;
This.newmethod (Scolor);
Delete This.newmethod;

THIS.name = sname;
This.sayname = function () {
alert (this.name);
}
}

var objb = new ClassB ("Color of OBJB", "Name of OBJB");
Objb.saycolor ();

OBJB is an example of CLASSB, how does OBJB have a color attribute and a Saycolor method?

First look at the instantiated code:

var objb = new ClassB ("Color of OBJB", "Name of OBJB");

Here ClassB is a class, the classb of which of course refers to objb this object;

In ClassB, the first three lines of code use ClassA, and then the ClassA is treated as a function, not a class.

If we call ClassA this function directly, then it is obvious that this in ClassA is the Window object, so we first copy the ClassA to the OBJB newmethod attribute (This.newmethod = ClassA),

And then call This.newmethod, this is the owener of this method is obviously already become this, and CLASSB in the current refers to OBJB, so at this time ClassA (strictly speaking Newmethod, because this is the copy after, and ClassA is already two methods This is the OBJB, which assigns the color property and the Saycolor method to the OBJB in the Newmethod call. Using the call and apply methods to implement inheritance is actually also a principle, call and apply can be seen as the way to change the owner of the method, and here ClassB the first three code is the role.

Iv. Class.create in the prototype1.6
Copy Code code as follows:

The Class.create method in prototype1.6 is roughly as follows:

var Class = {
Create:function () {
//

Function Klass () {
This.initialize.apply (this, arguments);
}

//

for (var i = 0; i < properties.length; i++)
Klass.addmethods (Properties[i]);

//

Return Klass;
}
};

At the time of use this is the case:


Copy Code code as follows:

var person = class.create ({
Initialize:function (name) {
THIS.name = name;
},
Say:function (message) {
Alert (THIS.name + ":" + message);
}
});

var Aperson = new Person ("name1");
Aperson.say ("Hello1");

The person actually passes the Klass (Klass is the local variable in class.create, a function) by class.create This method, and the parameters passed by Class.create (Initialize method and say method) are passed to Crea In the properties array in the Te method and by the Addmethods method, the Klass prototype owns these methods. So the most important place is also the most difficult to understand is: The Klass in the mean is what. It's not hard to get an answer when you think about it, person is actually Klass, and we're using the New keyword when instantiating the person object:

var Aperson = new Person ("name1");

This is equivalent to

var Aperson = new Klass ("name1");

Although Klass can not be accessed outside, but it is easy to explain the problem, Klass is a class rather than a simple function (we think so, because with the new keyword), then the Klass in this refers to the declaration of the instance, here is the Aperson, Aperson can have initialize method and say method through Klass prototype, in the process of new, will also execute the code in Klass, so initialize will execute when instantiated, that is, constructor. (In the Klass two this all refers to Aperson, why also through apply to call once?) This is mainly to transfer the parameters of the constructor, using the Apply method can be a number of variable parameters through the array easily to the Initialize method. )

V. Re-analysis of several examples

The examples I've seen from other articles are here to analyze:

1, run the following code
Copy Code code as follows:

function Outerfoo () {
This. name = ' Outer name ';

function Innerfoo () {
var name = ' Inner name ';
Alert (Name + ', ' + this.) Name);
}
return innerfoo;
}
Outerfoo () ();

The result shown is "Inner name, Outer name"

Outerfoo is a function (not a class), then the first sentence

This. name = ' Outer name ';

This refers to the Window object, so after Outerfoo () Window.name = ' Outer Name ';

and returns the Innerfoo, at which point the Innerfoo is also a function (not a class), when executing Innerfoo, this also refers to window, so the THIS.name value in Innerfoo is "Outer Name" (window. Name acts as a staging point, allowing Outerfoo to pass the value of "Outer name" to Innerfoo, and the value of name is the local variable "Inner name"

2, run the following code


Copy Code code as follows:

function Jsclass () {

This.m_text = ' division element ';
This.m_element = document.createelement (' DIV ');
This.m_Element.innerHTML = This.m_text;

if (this.m_Element.attachEvent)
This.m_Element.attachEvent (' onclick ', this. ToString);
else if (This.m_Element.addEventListener)
This.m_Element.addEventListener (' click ', this. Tostring,false);
Else
This.m_Element.onclick = this. ToString;
}

JSClass.prototype.Render = function () {
Document.body.appendChild (this.m_element);
}

JSClass.prototype.ToString = function () {
alert (This.m_text);
Alert (this = = window);
}

Window.onload = function () {
var JC = new Jsclass ();
Jc. Render ();
Jc. ToString ();
}

Click "Division Element" will display "undefined", under IE also show "true", other browsers also show "false".

Both instance declarations and invocation instance methods have nothing to say, and the element's Click event is bound to a method of an instance, so the method bound by AddEventListener is copied, so this refers to the HTML element, which has no m_text attribute (m_ The Text property belongs to the Jsclass instance, which belongs to JC), so clicking on the element shows that the Undefined,attachevent bound event will copy the function to the global, when this refers to the Window object, and the Click Element also displays "undefined". Only when calling JC. The ToString () method is, this refers to the JC object, because JC has m_text, so it can display "division element".

Vi. Summary

How do you quickly find this object in a code environment? I would like to note the following three aspects:
1, to know clearly for the function of each step is a copy or reference (call)
2. Know exactly what the owner of the function is (owner)
3. For a function, we need to figure out whether we use it as a function or as a class.

Add:
1. You can define functions directly on both instances and classes
2. You cannot use prototype to define functions on instances, you can only use prototype to define functions on a class
3. Functions defined directly on a class cannot use this to access the properties of an object
4. Functions established on the prototype of a class can be used with this, and functions defined within the class can use this, and the amount of function established on the object instance can be this
Copy code code as follows:

Window.alert=function (msg)
{
document.write (msg+ "<br>");
}
function Say ()
{
this.f= "props";
This.func3=function () {alert ("F3," +THIS.F);}
}
Say.func1=function () {alert ("func1," +this.f);}; Error, a function directly defined on the class, cannot use this
Say.prototype.func2=function () {alert ("Func2," +this.f);}
Say.func1 ();
(New Say ()). Func2 ();
SAY.FUNC2 (); Error, in a function defined with prototype, an object must be instantiated to invoke the
Say.func3 (); Error, the function defined on the class must be instantiated to invoke the
(New Say ()). FUNC3 ();
var obj={
Fld1:10,
Func1:function (msg) {alert (msg);},
Func4:function () {alert (this.fld1);}
}
Obj.prototype.func=function () {alert ("Func");}; The prototype definition object cannot be used on an Error instance object
Obj.func2=function () {alert ("Func2," +this.fld1);}; OK, the functions defined directly on the instance can use this to access the properties of the object
alert (obj.fld1);
OBJ.FUNC1 ("func1");
OBJ.FUNC2 ();
Obj.func4 ();

JavaScript this usage summary
Http://www.jb51.net/article/16863.htm

JavaScript This is an in-depth understanding
Http://www.jb51.net/article/19425.htm

JAVASCRIPT this detailed object-oriented
Http://www.jb51.net/article/17584.htm

Javascript this pointer
Http://www.jb51.net/article/19434.htm

How to use this keyword in javascript
Http://www.jb51.net/article/7954.htm

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.