首页 > 解决方案 > Assigning method to prototype not working

问题描述

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

OUTPUT

Test { name: 'Hello World' }
  1. why is the function sayName is not in the instance of the object.
  2. why is the me.callName() function call is not working

标签: javascriptfunctionconstructorclosuresprototype

解决方案


为什么函数 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());


推荐阅读