我尝试实现一个对象继承,其中每个对象共享相同的功能,但包含不同的值/容器.这样做我发现了一种奇怪的行为; 每个单独的对象都像魅力一样,但它们都有相同的选择.请澄清我的意思,我添加了一个示例代码.
我想要做的是从每个元素读取数据值并将其绑定到选项.在某些功能中需要这些才能正常工作!
<div class="first" data-value="first div"></div>
<div class="second" data-value="second div"></div>
<script>
var original = {
options: {
value: null,
factor: 13
},
init: function (container) {
this.options.value = container.getAttribute('data-value');
}
};
var variation = Object.create(original);
variation.options.factor = 37;
var firstDiv = Object.create(variation);
var secondDiv = Object.create(variation);
firstDiv.init(document.getElementsByTagName('div')[0]);
secondDiv.init(document.getElementsByTagName('div')[1]);
alert('firstDiv.options === secondDiv.options: ' + (firstDiv.options === secondDiv.options)); // but should be false!
</script>
Run Code Online (Sandbox Code Playgroud)
请注意,这只是显示实际对象的一小部分.在我看来,所有其他部分都是无关紧要的.
我希望问题很清楚.我也是Object.create()故意使用的.