我不知道一个更好的头衔,所以要解释一下, 假设你有一个“构造函数”
所以当第一个对象属性num
被更改时其他对象protype属性num
也应该改变
这当然适用于num
但如果num
是数字或字符串
如果num
在第一个对象中被覆盖,则原型的属性不会改变,因为原始变量作为值传递而不是通过引用传递,或者如果属性是对象并且将被覆盖新对象
所以我的问题是 是否有任何“整洁”的方法可以让对象从另一个对象继承属性的原始值,并让它们共享一个引用?
以下是一些示例代码,您可以跳过第一个代码,它在这里代码的完整性
/* Inheritance Helper*/
var base = (function baseConstructor() {
var obj = {
create:function instantiation() {
if(this != base) {
var instance = Object.create(this.pub);
this.init.apply(instance,arguments);
this.instances.push(instance);
return instance;
} else {
throw new Error("You can't create instances of base");
}
},
inherit:function inheritation() {
var sub = Object.create(this);
sub.pub = Object.create(this.pub);
sub.sup = this;
return sub;
},
initclosure:function initiation() {},
instances: [],
pub: {}
};
Object.defineProperty(obj,"init",{
set:function (fn) {
if (typeof fn != "function")
throw new Error("init has to be a function");
if (!this.hasOwnProperty("initclosure"))
this.initclosure = fn;
},
get:function () {
var that = this;
//console.log(that)
return function() {
if(that.pub.isPrototypeOf(this)) //!(obj.isPrototypeOf(this) || that == this))
that.initclosure.apply(this,arguments);
else
throw new Error("init can't be called directly");
};
}
});
Object.defineProperty(obj,"create",{configurable:false,writable:false});
Object.defineProperty(obj,"inherit",{configurable:false,writable:false});
return obj;
})();
/*Helpers*/
function merge (obj) {
if(arguments.length < 2)
throw new Error({msg:"At least 2 parameters needed"});
for ( var i = 1, ilen = arguments.length;i < ilen; i++)
for (var k in arguments[i])
obj[k] = arguments[i][k];
}
/*Helpers for workarounds*/
function tieProp (prop,obj) {
if(arguments.length < 3)
throw new Error({msg:"At least 2 Objects are needed"});
var ref = obj[prop];
for ( var i = 1,ilen = arguments.length;i<ilen;i++)
Object.defineProperty(arguments[i],prop,{
set: function (val) {
ref = val;
},
get: function () {
return ref;
}
});
}
因此,这是创建对象的部分
/*Example Code*/
var Series = base.inherit();
Series.init = function (specs) {
var _Series = this;
specs = specs ||{};
this.seasons = [];
var Season = Series.inherit();
Season.init = function(specs) {
var _Season = this;
specs = specs || {};
_Series.seasons.push(this);
merge(this,specs);
};
merge(this,specs);
Season.pub.score = this.score; // First way
Season.pub.stats = this.stats; // Second Way
tieProp("scoreTied",this,Season.pub); //Third Way
Season.pub.scoreSetter = this.scoreSetter; // Second Way
this.updateScore = function (score) { // Forth Way
this.scoreSetter = score;
Season.pub.scoreSetter = score;
};
tieProp("someObj",this,Season.pub); //Obj Example
this.addSeason = function (specs) {
Season.create(specs);
};
};
Series.pub.toString = function () {
return this.title + " has a score of " + this.scoreTied ;
};
var Futurama = Series.create({
title:"Futurama",
score:1, // 1.
scoreTied:2, // 2.
stats:{ //3.
score:3
},
scoreSetter:4,
someObj:{a:"b"}
});
Futurama.addSeason();
让我们在更改属性之前记录控制台输出
console.log("BeforeChange",Futurama.score + " - " + Futurama.seasons[0].score); //"1 - 1"
console.log(Futurama.scoreTied + " - " + Futurama.seasons[0].scoreTied); // "2 - 2"
console.log(Futurama.stats.score + " - " + Futurama.seasons[0].stats.score); // "3 - 3"
console.log(Futurama.scoreSetter + " - " + Futurama.seasons[0].scoreSetter); //"4 - 4"
console.log(JSON.stringify(Futurama.someObj) + " - " + JSON.stringify(Futurama.seasons[0].someObj)); //"{"a":"b"} - {"a":"b"}"
然后更改Futurama
Futurama.score = 2; //TFirst way // This will fail
Futurama.scoreTied = 3; //Second way
Futurama.stats.score = 4; // Third way
Futurama.updateScore(5); // Forth Way
Futurama.someObj = {b:"a"}; // Object replacement
并记录下来
console.log("After Change",Futurama.score + " - " + Futurama.seasons[0].score); // 2 - 1
console.log(Futurama.scoreTied + " - " + Futurama.seasons[0].scoreTied); // 3 - 3
console.log(Futurama.stats.score + " - " + Futurama.seasons[0].stats.score); //4 -4
console.log(Futurama.scoreSetter + " - " + Futurama.seasons[0].scoreSetter); //5 - 5
console.log(JSON.stringify(Futurama.someObj) + " - " + JSON.stringify(Futurama.seasons[0].someObj)) ; //"{"b":"a"} - {"b":"a"}"
因此,当使用
时,这是可能的 就像function tieProp (prop,obj) {...
但我不知道在这种情况下使用Object.defineProperty是否合适,我是否真的必须设置属性描述符让一些属性共享一个对原始值的引用?
就像Season.pub.stats = this.stats; // Second Way
这没关系,但我对此不太满意,因为我必须将属性移动到另一个,这会带走一些命名自由,在这个例子中,我想{{ 1}}作为Futurama的分数在score
而不是Futurama.score
*为属性编写setter,它只设置Objects的两个值
*喜欢Futurama.stats.score
*
但我宁愿远离这个,因为我必须向Object添加方法
我不知道我根本不应该做这样的事情,或者我是否只是错过了 真的很简单的方法吗?
任何建议或指向正确方向的人都会非常感激
并提前感谢您的答案和耐心阅读
继承人JSBin来摆弄
答案 0 :(得分:0)
使用命名函数作为属性值来共享原子元素的实例:
foo = {"1":1}
bar = {"1": function baz() { return foo["1"] } }
foo["1"] = 2;
foo["1"] === bar["1"]();
<强>参考强>