JS self=this

时间:2023-03-09 17:13:59
JS self=this

1.每个函数都会有自己的this和arguments;this对象绑定运行环境,arguments绑定调用参数。

2.全局函数:this和全局环境绑定,浏览器指向全局window对象(node.js中指向全局global对象)。

3.类成员函数:this和实例对象绑定,指向类实例对象。

4.类成员函数中的局部函数:this和全局环境绑定,指向全局window对象(node.js中指向全局global对象)。也就是在这种情况下,如果需要使用到类实例对象的引用,就需要将类实例对象的引用this记录下来,提供给该局部函数使用。(个人理解为闭包的作用。)

下面例子在node.js上运行,在浏览器上运行请将global替换为window。

5.全局函数的例子:

var g_func = function(){
console.log(this == global);
} g_func();

输出

true

6.类成员函数例子

var g_object = function(){
this.func = function(){
console.log("func this == global : ",this == global);
} this.no_self_func = function(){
var inner_func = function(){
console.log("no_self_func this == global : ",this == global);
} inner_func();
} this.self_func = function(){
var self = this;
var inner_func = function(){
console.log("self_func this == global : ",this == global);
console.log("self_func self == global : ",self == global);
} inner_func();
}
} var obj = new g_object();
obj.func();
obj.no_self_func();
obj.self_func();

输出

func this == global :  false

no_self_func this == global :  true

self_func this == global : true
self_func self == global : false

PS:这种特性和lua很像。

以上。