【发布时间】:2018-07-31 04:15:43
【问题描述】:
在func2下面的代码sn-p中,func1应该是the shorthand method syntax。
问题1:为什么obj1 包含prototype 对象而obj2 不包含(而两者都有__proto__ 对象)?
问题 2:这三个对象都是原型对象吗?
问题 3:为什么 obj2 没有原型函数这一事实不会影响它绑定 this 的方式?
关于obj3:obj3 可供参考,因为它在没有prototype 功能方面等同于obj2。它只是以不同的方式绑定this(在obj1 和obj1 this 中“由调用确定,但不是由封闭上下文”确定,并且在obj3 中this 在词法上绑定到window 对象. 两者都是nicely described in this article.)。
代码sn-p:
// Using the basic method definition
const obj1 = {
foo: function() {
console.log("This is foo");
},
bar: function() {
console.log("This is bar");
this.foo();
}
};
// Using shorthand method syntax
const obj2 = {
foo() {
console.log("This is foo");
},
bar() {
console.log("This is bar");
this.foo();
}
};
// Using arrow function
const obj3 = {
foo: () => console.log("This is foo"),
bar: () => {
console.log("This is bar"); this.foo();
}
};
/* Test */
obj1.bar(); // works!
obj2.bar(); // works!
obj3.bar(); // throws TypeError (this.foo is not a function)
我是如何发现func1 是原型函数而func2 不是:
我在 Chrome Dev Tools 的控制台中查看了两者,发现 prototype 对象仅包含在其中一个中:
我查看了this 和this 关于__proto__ 和prototype 之间区别的问题,但我的问题是关于为什么在使用应该等效的语法后后者不存在。
【问题讨论】:
-
箭头函数没有自己的上下文,所以你不能像普通的成员方法一样对待它们,除非它们的声明范围是在构造函数或其他成员方法中
标签: javascript object javascript-objects