【发布时间】:2018-03-11 13:08:01
【问题描述】:
我正在尝试深入了解 'this' 在 javascript 中的工作原理。 到目前为止,我对这个的了解是,
每个函数都有属性,每当函数执行时,它都会重新定义 this 属性。
this是指调用函数的对象(包括浏览器中的window对象)。
this 指的是对象的范围(定义对象的地方)而不是指对象本身,如果在定义函数时使用箭头语法,因为箭头函数没有新定义自己的this。
以下示例有助于理解 this
的行为class Example {
constructor() {
this.name = 'John';
}
method1() { //case1 : Closure
console.log(this.name);
function method2() {
console.log(this.name);
}
method2();
}
}
const a = new Example()
a.method1();
function testing(callback) {
return callback();
}
class Example2 {
constructor() {
this.name = 'John';
}
method1() { //case2: callback
console.log(this.name);
testing(function() {
console.log(this.name);
})
}
}
const b = new Example2()
b.method1();
function testing(callback) {
return callback();
}
class Example3 {
constructor() {
this.name = 'John';
}
method1() { //case3: arrow syntax callback
console.log(this.name);
testing(() => {
console.log(this.name);
})
}
}
const c = new Example3()
c.method1(); // logs 'John'
// logs 'John'
function testing(callback) {
return callback();
}
class Example4 {
constructor() {
this.name = 'John';
}
method1() { // case4: calling method as callback
console.log(this.name);
}
render() {
testing(this.method1)
}
}
const d = new Example4()
d.render()
function testing(callback) {
return callback();
}
class Example5 {
constructor() {
this.name = 'John';
this.method1 = this.method1.bind(this);
}
method1() { //case5: bind method && calling method as callback
console.log(this.name);
}
render() {
testing(this.method1)
}
}
const d = new Example5()
d.render()
我想知道上述情况有何不同,以及 this 在每个内部函数和回调中指的是什么。你能解释一下吗?谢谢你:)
【问题讨论】:
-
@jonsilver 他不问“如何”,而是问“为什么”。
标签: callback closures this bind arrow-functions