javascript - 为什么使用速记方法语法的方法不包含原型(prototype)对象

标签 javascript object javascript-objects

在下面的代码片段中,func2 应该是 the shorthand method syntax对于 func1

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

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

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

关于obj3:obj3是供引用的,因为它等同于obj2没有一个 prototype 函数。它只是以不同方式绑定(bind) this(在 obj1obj1 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 对象只包含在其中一个中:

Screenshot of console with obj1 and obj2

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

最佳答案

Why does obj1.bar contain the .prototype Object and obj2.bar does not?

因为它是一个方法定义。方法不是构造函数,它们不需要构造函数。 (这是相同的 for class methodsfor 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/

相关文章:

javascript - 我怎样才能用nodejs获得discord get membercount

javascript - 在我的nodeJS应用程序中压平树上的空组

javascript - 调用 jQuery AJAX 中包含的方法,该方法包含在同一类的方法中

javascript - 数据格式化问题 : Array to Object. 有什么简单的方法吗?

c++ - 遍历对象列表 C++

javascript - Jquery/JS - 为每个 Div 动态创建对象

javascript - 将对象及其方法分配给原型(prototype)

php - 如何在 Netbeans 中包含来自单独远程文件夹的文件(PHP 开发)

JavaScript 时间跨度控制

javascript - 如何根据下拉选择隐藏和显示内容