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' }
- 为什么函数 sayName 不在对象的实例中。
- 为什么 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/