javascript - 将方法分配给原型(prototype)不起作用

标签 javascript function constructor closures prototype

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() 函数调用不起作用

最佳答案

why is the function sayName is not in the instance of the object.

因为你没有分配它。

this.sayName = sayName;

why is the me.callName() function call is not working

我不知道它对我有用

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());

关于javascript - 将方法分配给原型(prototype)不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58842013/

相关文章:

Javascript:在函数外获取 `this`

JavaScript var 可见性

函数参数上的 Python 描述符(__get__、__set__)

javascript - (CSS): can i trigger two of css events simultaneously by just triggering one event or the class name that two of events are included?

javascript - Node.js - 来自 ajax 端点的有序 JSON 数据顺序错误,缓存不是问题

javascript - process.env 在 `npm run build` (Ubuntu) 时不包含 ENV VARS

c++ - 在两个构造函数之间进行选择

javascript - 同一条信息重复3次

c++ - 不可能的构造函数

c++ - 向类的构造函数添加虚拟参数以解决调用歧义是否违反任何规则?