我是js的新手.我正在尝试使用构造函数来创建一个对象.这是我的代码
function player(name,age,rank)
{
this.name=name;
this.age=age;
this.rank=rank;
this.sayEverything=function()
{
return "The name of the player is " + this.name + "the age is " + this.age + "the rank is " + this.rank;
}
Run Code Online (Sandbox Code Playgroud)
现在我正在添加这样的新属性
player.matchReady=true;
Run Code Online (Sandbox Code Playgroud)
现在我创建一个像这样的对象
var kaka=new player("kaka",22,3,false);
Run Code Online (Sandbox Code Playgroud)
当我写这个
document.write('kaka is match ready-->' + kaka.matchReady);
Run Code Online (Sandbox Code Playgroud)
它给了我这个输出 卡卡准备匹配 - >未定义
为什么它给我未定义?我没有正确添加新属性吗?请告诉我.谢谢.
代替 player.matchReady=true;
做, player.prototype.matchReady = true;
这样所有玩家都将匹配就绪默认为true;
您也可以将函数放入原型中.
player.prototype.sayEverything=function()
{
return "The name of the player is " + this.name + "the age is " + this.age + "the rank is " + this.rank;
}
Run Code Online (Sandbox Code Playgroud)
您可以将prototype视为脚手架,在该脚手架上概述了对象在实例化时应具有的所有属性和函数.所有这些默认值对于所有对象都是相同的.
在函数中添加函数时,在实例化新对象时,所有这些函数都会在内存中重复.
在可能的情况下,当不需要作用域时,尝试添加类似你的通用函数sayEverything()(请将其重命名以toString()符合约定)到原型.
这样所有玩家对象都可以使用相同的功能.哪个内存更有效率.
| 归档时间: |
|
| 查看次数: |
60 次 |
| 最近记录: |