Recently work and read a lot of JS in the ' This ', I think it is necessary to comb a bit.
1. When used in the global scope, this points to the Global object window.
var name= ' aaa '; alert (this. name); // AAAalert (window.name); // AAAAlert (this ===window); // true
2. When a function is defined in the global scope and this is used in the function, the environment object that the function executes is the Global object window, so this also points to window.
var name= ' aaa '; function Sayname () { alert (this. name); // AAA alert (window.name); // AAA Alert (this ===window); // true }sayname ();
3. It is also possible to point this in the function to other scopes (environment objects) by using the Apply or call method of the function.
var obj={name: ' BBB '}var name= ' aaa '; function Sayname () { alert (this. name); // BBB Alert (this ===window); // false Alert (this ===obj); // true }sayname.apply (obj);
When the scope of the sayname is changed, the This object also points to the scope of the Sayname obj, so this point is to obj.
4. When the function is used as a constructor, this is used in the constructor, and this refers to the new object created through the constructor.
function Student (name) { this. name=name;} var stu1=New Student (' abc ');
alert (stu1.name); // ABC
When you create an object by using a constructor, a new object is created first, and then the scope of the constructor is assigned to the new object, so this point points to the new object.
5. When the function acts as a method of an object, use this in the function, at which point this is the object.
var student={ name:' abc ', sayname:function() { alert (this). name); // ABC Alert (this ===student); // true }}student.sayname ();
Summary: This refers to an environment object in which the function data has been executed.
The ' this ' in JavaScript