函数上下文 (this 指向)看这一篇就够了
-
简单调用,函数直接圆括号执行,函数上下文是 window(this 指向 window);
var number = 1111 function getNumber(){ this.number = 2222 console.log(this.number) } getNumber() // '2222', this 指向 window console.log(number) // '2222' number 的值被改变
-
函数(非箭头函数)作为对象的方法,对象最后打点调用 obj.fn() ,那么函数上下文是这个对象 obj。
var name = 'jerry' function say(){ console.log(this.name) } var obj = { name: 'tom', say: say } obj.say() // 'tom', this 指向 obj say() // 相当于 window.say(), this 指向 window
-
计时器的回调函数中的上下文是 window
var name = 'jerry' function say(){ setTimeout(function(){ console.log(this.name) }, 1000) } var obj = { name: 'tom', say: say } obj.say() // 'jerry', 定时器执行,this 指向 window
-
call & apply 将 this 指向 第一个参数
function say(){ console.log(this.name) } var obj = { name: 'tom', say: say } say.call(obj, 1,2,3,4) say.apply(obj, [1,2,3,4])
-
bind 方法将 this 永久绑定到第一个参数
function fn(){ return this.name; } var g = fn.bind({ name: "tom" }); console.log(g()); // tom var h = g.bind({ name: "jerry" }); // bind只生效一次! console.log(h()); // tom
-
箭头函数 this 指向其创建时所处上下文。在全局代码中,它将被设置为全局对象
箭头函数本身没有构造函数,是不能使用
new
关键字创建实例的
var foo = () => this;
var obj = { foo: foo };
var obj2 = {
foo: () => this
}
console.log(obj.foo()); // Window
console.log(obj2.foo()); // Window
var obj = {
bar: function() {
var x = () => this;
return x;
}
};
obj.bar()() // obj
-
构造函数: new 运算符
new 运算符执行的函数叫做构造函数,也可以是一个类,new 函数返回的结果就是一个对象。构造函数中的 this 指向这个被创建的新对象。
new 运算符执行规则:
- new 运算符执行函数的时候,函数内部默认创建一个空对象 People
- 函数上下文指向这个对象 People
- 执行函数体 (this.name, this.age ...)
- 构造函数默认返回这个对象本身 People {name: 'jerry', age: 20}
function Person() { this.name = 'jerry' this.age = 20 this.sayHi = function(){ console.log(this) } } var obj = new Person(); // new执行函数, this 指向构造函数 Person console.log(obj); // Person obj.sayHi()
网友评论