【问题标题】:Why does a method using the shorthand method syntax not contain a prototype object为什么使用速记方法语法的方法不包含原型对象
【发布时间】:2018-07-31 04:15:43
【问题描述】:

func2下面的代码sn-p中,func1应该是the shorthand method syntax

问题1:为什么obj1 包含prototype 对象而obj2 不包含(而两者都有__proto__ 对象)?

问题 2:这三个对象都是原型对象吗?

问题 3:为什么 obj2 没有原型函数这一事实不会影响它绑定 this 的方式?

关于obj3obj3 可供参考,因为它在没有prototype 功能方面等同于obj2。它只是以不同的方式绑定this(在obj1obj1 this 中“由调用确定,但不是由封闭上下文”确定,并且在obj3this 在词法上绑定到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 对象仅包含在其中一个中:

我查看了thisthis 关于__proto__prototype 之间区别的问题,但我的问题是关于为什么在使用应该等效的语法后后者不存在。

【问题讨论】:

标签: javascript object javascript-objects


【解决方案1】:

为什么obj1.bar 包含.prototype 对象而obj2.bar 不包含?

因为它是一个方法定义。方法不是构造函数,它们不需要构造函数。 (顺便说一句,for class methodsfor arrow functions 是一样的。)
obj2 中,您使用了function 表达式,它创建了一个可用作构造函数的函数(ES5 中一直如此)。

这三个对象都是原型对象吗?

对象不是“原型对象”。每个对象都可以用作其他对象的原型。

为什么obj2.bar 没有.prototype 的事实不会影响它绑定 this 的方式?

为什么会这样?它仍然是一个方法,应该具有动态的this 值,否则无法共享。

只有您在obj3 中使用的箭头函数在这方面具有特殊行为。详情请见Methods in ES6 objects: using arrow functions

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-23
    • 2011-11-22
    • 1970-01-01
    • 1970-01-01
    • 2023-01-05
    • 2011-12-08
    • 1970-01-01
    相关资源
    最近更新 更多