在下面的代码片段中,func2
应该是 the shorthand method syntax对于 func1
。
问题 1:为什么 obj1
包含 prototype
对象而 obj2
不包含(虽然两者都有__proto__
对象)?
问题2:这三个对象都是原型(prototype)对象吗?
问题 3:为什么 obj2
没有原型(prototype)函数这一事实不会影响它绑定(bind) this
的方式?
关于obj3
:obj3
是供引用的,因为它等同于obj2
没有一个 prototype
函数。它只是以不同方式绑定(bind) this
(在 obj1
和 obj1
this
中,“由调用决定,而不是由包含上下文”,在 obj3
中,this
在词法上绑定(bind)到 window
对象。两者都是 nicely described in this article .)。
代码片段:
// 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
是原型(prototype)函数而 func2
不是:
我在 Chrome Dev Tools 的控制台中查看了两者,发现 prototype
对象只包含在其中一个中:
我看了this和 this关于 __proto__
和 prototype
之间区别的问题,但我的问题是关于为什么后者在使用应该等效的语法后不存在。
最佳答案
Why does
obj1.bar
contain the.prototype
Object andobj2.bar
does not?
因为它是一个方法定义。方法不是构造函数,它们不需要构造函数。 (这是相同的 for class
methods 和 for arrow functions ,顺便说一句。)
在 obj2
中,您使用了一个 function
表达式,它创建了一个可以用作构造函数的函数(在 ES5 中一直如此)。
Are all three objects prototype objects?
对象不是“原型(prototype)对象”。每个对象都可以用作其他对象的原型(prototype),也可以不。
Why does the fact of
obj2.bar
not having a.prototype
not influence the way in which it binds this?
为什么会这样?它仍然是一个应该具有动态 this
值的方法,否则无法共享。
只有您在 obj3
中使用的箭头函数在这方面具有特殊行为。参见 Methods in ES6 objects: using arrow functions了解详情。
关于javascript - 为什么使用速记方法语法的方法不包含原型(prototype)对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48891399/