JavaScrip this 的四种绑定方式
-
默认绑定
// 非严格模式, 独立函数调用的 this 全部指向 window function foo() { console.log(this); } // window.foo(); foo(); // window // 不管定义的位置, 主要是谁调用 let obj = { name: "why", fn: function () { console.log(this); } } let bar = obj.fn; bar(); // window
-
显式绑定( call, apply, bind )
function foo() { console.log(this); } let obj = { name: "why" } foo.call(obj); foo.apply(obj); // 返回一个新的函数, 新函数的 this 被指定为 bind() 的第一个参数, 而其余参数将作为新函数的参数 foo.bind(obj)();
-
隐式绑定
let obj = { name: "why", foo: function () { console.log(this); console.log(this.name); } } obj.foo();
-
new 关键字绑定
/** * 构造函数 * @param name * @param age * @constructor */ function Person(name, age) { this.name = name; this.age = age; this.foo = function () { console.log(this.name, this.age); } } /** * new 关键字的原理 * 1. 在构造函数内部 let obj = {}; * 2. this = obj; * 3. 执行函数 * 4. return obj; */ new Person("why", 18).foo();