javascript - 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' }
- why is the function sayName is not in the instance of the object.
- why is the me.callName() function call is not working
解决方案
为什么函数 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());
推荐阅读
- javascript - 在javascript中返回'Yes','No'而不是true,false的奇怪实现
- java - Intellij IDEA 社区中使用 Workday Extend 的插件出现 IDE 致命错误但显示 java 错误?
- php - 如何将 CURL 转换为 Guzzle HTTP?
- typescript - 如何将使用一个数据集的工具提示添加到使用 d3 中的另一个数据集的图表中
- vba - 当计数器在表中命中 0 时循环遍历 MS-Access 中的表
- mysql - MySQL 意外关闭 xampp 。这可能是由于端口阻塞 有人可以帮忙,以便我可以开始使用 xampp 服务器吗?
- asp.net - 在 Dockerfile 中安装 microsoft-net-sdk-blazorwebassembly-aot 时出错
- r - 减少绘图 X 标签中的距离(R:ggplot2)
- css - React 插件,如何确保网站样式不会覆盖我的样式
- javascript - 在 localhost 上运行的网站无法找到 js 文件