本文已参与「新人创作礼」活动,一起开启掘金创作之路。
-
this的多种嘴脸
-
第一定律:(1) 以方法方式调用时,this是绑定宿主对象
var obj = { method:() =>{ console.log(this) } } obj.method(); // obj -
(2) 以函数方式调用时,this是window对象 (调用全局函数)
function fun(){ console.log(this) } fun() // window全局变量或函数都相当于window对象的属性,这里 this 绑定到 window 对象就显而易见,很容易理解了。相当于方法调用模式的一个特例,不违背第一定律
-
(3) 以构造函数方式调用时,this是创建的新对象
function Person(name, age){ this.name = name; this.age = age; } var john = new Person('John', 38); //this => john使用 new 调用,就会创建一个连接到该函数原型 prototype 属性的新对象,再把 this 绑定到该对象
-
(4) 以call和apply调用时,this是传入的那个对象 (第一个参数)
// call方式 function fun (a,b){ console.log(this) } let obj = { ... } fun.call(obj,1,2) // this => obj 这个参数// apply方式 function fun (a,b){ console.log(this) } let obj = { ... } fun.apply(obj,[1,2]) // this => obj 这个参数apply 和 call 的区别
- apply要求第二个参数必须是数组
- call则没这么严格,第二个参数是函数的入参(第一个第二个第三个第四个第五个第六个)
-
在严格模式下,
this将保持他进入执行上下文时的值,所以下面的this将会默认为undefined
function f2(){
"use strict"; // 这里是严格模式
return this;
}
f2() === undefined; // true
所以,在严格模式下,如果 this 没有被执行上下文(execution context)定义,那它将保持为 undefined。
但是,如果用
window来调用的话,this就是window了。
function f2(){
"use strict"; // 这里是严格模式
return this;
}
console.log(window.f2()) // window
bind 方法
ECMAScript 5 引入了 Function.prototype.bind。调用 f.bind(someObject) 会 创建一个与 f 具有相同函数体和作用域的函数,但是在这个新函数中,this 将永久地被绑定到了 bind 的第一个参数,无论这个函数是如何被调用的。
【this 一旦被绑定到了 bind 的第一个参数,后面将无法修改 this ,无论这个函数是如何被调用的】
function f(){
return this.a;
}
var 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