gpt4 book ai didi

javascript - 部分继承 - 在对象之间共享原始值

转载 作者:行者123 更新时间:2023-11-28 09:28:35 25 4
gpt4 key购买 nike

我不知道更好的标题,所以解释一下,假设你有一个“构造函数”

  • 实例化一个对象并设置一些属性
    • 在实例化过程中,另一个对象被创建
    • 此对象原型(prototype)应该将第一个对象的一些属性隐藏到其子对象

因此,当第一个对象属性 num 更改时,其他对象原型(prototype)属性 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"}"

所以,当使用时这是可能的

  • Object.defineProperty 为属性提供 getter 和 setter

就像 function tieProp (prop,obj) {...

但我不知道在这种情况下使用 Object.defineProperty 是否合适,我是否真的必须设置属性描述符才能让某些属性共享对原始值的一个引用?

  • 将所有原始值包装在一个对象中,该对象将作为引用传递并更改此对象属性

就像Season.pub.stats = this.stats;//第二种方式

这没问题,但我对此不太满意,因为我必须将属性移动到另一个属性中,这会剥夺一些命名自由,在这个例子中,我想要 score 作为 Futurama 的分数,位于 Futurama.score 中,而不是位于 Futurama.stats.score

*为属性编写 setter ,它只是设置对象的两个值

*就像 this.updateScore = function (score) {//Forth Way *

但我宁愿远离这个,因为我必须向对象添加方法

我不知道我是否根本不应该做这样的事情,或者我是否只是错过了这样做的方法真的很简单??

任何正确方向的建议或指出将不胜感激

提前感谢您的回答和耐心阅读本文

这是 JSBin摆弄

最佳答案

使用命名函数作为属性值来共享原子元素的实例:

foo = {"1":1}
bar = {"1": function baz() { return foo["1"] } }

foo["1"] = 2;
foo["1"] === bar["1"]();

引用文献

关于javascript - 部分继承 - 在对象之间共享原始值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13970913/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com