87,910
社区成员
发帖
与我相关
我的任务
分享
var obj1 = {};
var obj2 = {};
var obj3 = {};
// 传入什么,返回什么
function unchange(x) {
return x;
}
function doSth() {
this.flag = "做个记号";
if (this == window)
return alert("this == window");
for (var x in window) {
if (this == window[x])
return alert("this == " + x);
}
}
// doSth 已定义好,但函数中的 this 是指向谁还是个未知数,具体因调用方式不同而异
// 直接调用, this 指向全局对象,浏览器中执行时,就是 window;
doSth();
// 作为 obj1 的属性调用时,this 指向 obj1
obj1.doSth = doSth;
obj1.doSth();
// 作为函数返回值传出时,已不当作 obj1 的属性, 相当于直接调用。this 指向 window
unchange(obj1.doSth)();
// 作为构造函数使用时,this 指向刚刚创建的对象
var newObject = new doSth();
alert(newObject.flag);
// call, apply 调用,可转移 this 指向
doSth.call(obj2); // 指向 obj2
doSth.apply(obj3, []); // 指向 obj3