JavaScript的this
函数中的this 通常指向一个对象,这个对象根据这个函数是如何被调用来决定。
`function foo() { console.log( this.bar );
}
var bar = "global";
var obj1 = { bar: "obj1",
foo: foo };
var obj2 = { bar: "obj2"
};
foo(); // “全局的”
obj1.foo(); // "obj1"
foo.call( obj2 ); // "obj2"
new foo(); // undefined`
关于如何设置 this 有 4 条规则,上述代码中的最后 4 行展示了这 4 条规则。
(1) 在非严格模式下,foo() 最后会将 this 设置为全局对象。在严格模式下,这是未定义的 行为,在访问 bar 属性时会出错——因此 "global" 是为 this.bar 创建的值。
(2) obj1.foo() 将 this 设置为对象 obj1。
(3) foo.call(obj2) 将 this 设置为对象 obj2。
(4) new foo() 将 this 设置为一个全新的空对象。
浙公网安备 33010602011771号