var x = 1;
functiontest(){
alert(this.x);
}
test(); 这个this指向的是全局对象(window)
在默认情况(非严格模式下,未使用 'use strict'),没找到直接调用者,则this指的是 window (约定俗成)
基于函数的实例化对象。
var x = 1functiontest(){this.x = 2//this指向的是实例化对象即test.propotype
}
var obj = new test()
alert(x) //window.x
alert(obj.x) //函数的内部变量
因为 test.propotype = obj.__proto__
apply ,call,bind调用 ,作用是改变函数的调用对象,第一个参数为函数的对象
var x = 0;
var obj = {
x : 1,
test :functiontest(){
alert(this.x);
}
}
obj.test.apply(); //0
apply()的参数为空时,默认调用全局对象。
因此,这时的运行结果为0,证明this指的是全局对象。
如果把最后一行代码修改为
o.m.apply(obj); //1
一个混合的例子 作为对象方法调用,this 指代上级对象
var name = "The Window";
var object = {
name : "My Object",
getNameFunc : function(){
console.log(this.name) // 作为对象方法调用,this 指代上级对象指向objectreturnfunction(){returnthis.name; //this是这个匿名函数,没有直接调用者,this指向window
};
}
};
alert(object.getNameFunc()()); // "The Window";
es6中的箭头函数this1、箭头函数没有自己的this, 它的this是继承而来; 2、this指向创建这个函数的创建环境。 3、一般都react,es6开发中使用箭头函数,那么函数中的this指向的是这个创建的类,所处的对象,也就是所谓的宿主对象。平常声明的函数 var x = 1; function test(){ alert(this.x);...