我有一个对象,x.我想把它复制为对象y,这样改变y就不要修改了x.我意识到复制从内置JavaScript对象派生的对象将导致额外的,不需要的属性.这不是问题,因为我正在复制我自己的一个文字构造的对象.
如何正确克隆JavaScript对象?
我正在做一个基于文本的蹩脚游戏,我做了一个像这样的对象玩家:
var player = {
displayText: "<span>you</span>",
currentPosition: 0,
level: 1,
health: function() { return 10 + (this.level * 15) },
strength: function() { return this.level * 5 },
hitRating: 4
}
Run Code Online (Sandbox Code Playgroud)
我的理解是你可以给一个对象一个函数作为属性.
但是,当alert(player.health)我得到:
function() { return 10 + (this.level * 15) }
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?您是否无法以这种方式声明对象属性?有没有办法自动生成player.health以后调用的任何时间的值?
我刚刚发现Object.defineProperty并且因为我对 C# 最熟悉,所以我想在构造函数中使用访问器属性,例如:
function Base(id) {
var _id = id;
Object.defineProperty(this,"ID",{
get: function() { return _id; },
set: function(value) { _id = value; }
})
}
function Derived(id, name) {
var _name = name;
Base.call(this,id);
Object.defineProperty(this,"Name",{
get: function() { return _name; },
set: function(value) { _name = value; }
})
}
Derived.prototype = Object.create(Base.prototype);
Derived.constructor = Derived;
var b = new Base(2);
var d = new Derived(4,"Alexander");
console.log(b.ID);
console.log(d.ID, d.Name);
d.ID = 100;
console.log(d.ID, d.Name);Run Code Online (Sandbox Code Playgroud)
这打印:
2
4 …