this
全局上下文
无论是否在严格模式下,在全局执行上下文中(在任何函数体外部)this 都指代全局对象。
函数上下文
在函数内部,this的值取决于函数被调用的方式。
简单调用
不在严格模式下,且 this 的值不是由该调用设置的,所以 this 的值默认指向全局对象。
function f1() { return this; }
//在浏览器中: f1() === window; //在浏览器中,全局对象是window //在Node中: f1() === global;
在严格模式下,this将保持他进入执行上下文时的值。如果 this 没有被执行上下文(execution context)定义,那它将保持为 undefined。
function f2() { "use strict"; // 这里是严格模式 return this; }
f2() === undefined; // true
如果要想把 this 的值从一个上下文传到另一个,就要用 call 或者apply方法。
// 将一个对象作为call和apply的第一个参数,this会被绑定到这个对象。 var obj = { a: 'Custom' }; // 这个属性是在global对象定义的。 var a = 'Global'; function whatsThis(arg) { return this.a; // this的值取决于函数的调用方式 } console.log(whatsThis()); // 'Global' console.log(whatsThis.call(obj)); // 'Custom' console.log(whatsThis.apply(obj)); // 'Custom'
当一个函数在其主体中使用 this 关键字时,可以通过使用函数继承自Function.prototype 的 call 或 apply 方法将 this 值绑定到调用中的特定对象。
function add(c, d) { return this.a + this.b + c + d; }
var o = { a: 1, b: 3 }; // 第一个参数是作为‘this’使用的对象 // 后续参数作为参数传递给函数调用 console.log(add.call(o, 5, 7)); // 1 + 3 + 5 + 7 = 16 // 第一个参数也是作为‘this’使用的对象 // 第二个参数是一个数组,数组里的元素用作函数调用中的参数 console.log(add.apply(o, [10, 20])); // 1 + 3 + 10 + 20 = 34
使用 call 和 apply 函数的时候要注意,如果传递给 this 的值不是一个对象,JavaScript 会尝试使用内部 ToObject 操作将其转换为对象。
function bar() { console.log(Object.prototype.toString.call(this)); } //原始值 7 被隐式转换为对象 console.log(bar.call(7)); // [object Number]
bind方法
ECMAScript 5 引入了 Function.prototype.bind。调用f.bind(someObject)会创建一个与f具有相同函数体和作用域的函数,但是在这个新函数中,this将永久地被绑定到了bind的第一个参数,无论这个函数是如何被调用的。
function f() { return this.a; } v ar g = f.bind({ a: "azerty" }); console.log(g()); // azerty var h = g.bind({ a: 'yoo' }); // bind只生效一次! console.log(h()); // azerty var o = { a: 37, f: f, g: g, h: h }; console.log(o.f(), o.g(), o.h()); // 37, azerty, azerty