【问题标题】:Assigning method to prototype not working为原型分配方法不起作用
【发布时间】:2019-11-13 16:58:18
【问题描述】:
function Test(){
  this.name = "Hello World";
  function sayName(){
    return this.name;
  }
}
Test.prototype.callName = function(){
    return `Hello my name is, ${this.name}`;
}
const me = new Test();
me.callName();
console.log(me);

输出

Test { name: 'Hello World' }
  1. 为什么函数 sayName 不在对象的实例中。
  2. 为什么 me.callName() 函数调用不起作用

【问题讨论】:

  • console.log(me.callName()) ...
  • 谢谢@JonasWilms。你能回答第一个问题背后的逻辑吗?比如为什么我不能在“我”上调用 sayName()

标签: javascript function constructor closures prototype


【解决方案1】:

为什么函数 sayName 不在对象的实例中。

因为你没有分配它。

this.sayName = sayName;

为什么 me.callName() 函数调用不起作用

IDK 对我有用

function Test(){
  this.name = "Hello World";
  this.sayName = function sayName(){
    return this.name;
  }
}
Test.prototype.callName = function(){
    return `Hello my name is, ${this.name}`;
}
const me = new Test();
console.log(me.sayName());
console.log(me.callName());

【讨论】:

【解决方案2】:

这是因为您正在使用 new 关键字创建 Test() 的对象。当您创建一个 使用 new 关键字的对象实例

  1. 创建了一个新的空对象
  2. 空对象的原型链接与Test链接
  3. this 的值绑定到Test.prototype
  4. 每当提到这一点时,它都会使用新创建的对象执行构造函数
  5. 返回新创建的对象
  6. 如果Test() 有一个返回值,则返回该值。

因此,在此过程中,您实际上将this 的值永久绑定到Test,因此this.name 可以变为Test.name

如果您只调用 me = Test 而不使用 new,则不会发生 this 绑定。在这种情况下,this 实际上将引用全局范围。

如果你写了this.sayName = function sayName(){...},你可以访问sayName

me.callName 通过 行为委托 工作。这是 js 的功能,如果该行为未在相关对象上定义,则您可以在其中指示将行为委托给的对象。 Test.callName 不存在,因此它遍历原型链接并在使用的prototype 对象中找到callName 函数。

最后,我真的建议你学习newObject.createprototype degation的内部工作原理。尽管 class 关键字当前存在于 javascript 中,但它只是围绕 new 关键字如何工作的语法糖,与 classobject oriented languages 中的工作方式相同,例如 java 。 IMO,我建议您了解更多关于 new , Object.create 的信息,因为它们在现代代码中也非常常用:)

this post is worth noting

【讨论】:

    猜你喜欢
    • 2014-05-26
    • 1970-01-01
    • 1970-01-01
    • 2011-12-30
    • 1970-01-01
    • 2016-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多