在 MDN 上,我发现了以下代码片段,注释为“回收同一对象”:
// recycling same object
function withValue(value) {
var d = withValue.d || (
withValue.d = {
enumerable: false,
writable: false,
configurable: false,
value: null
}
);
d.value = value;
return d;
}
有人可以用通俗易懂的语言解释一下这段代码的真正作用吗?对于初学者来说不是那么明显。谢谢。
以及来源网址:enter link description here
另外,为什么不把 d
放在 withValue
函数本身上,为什么不把它放在 withValue
的原型(prototype)上,比如:
var d = withValue.prototype.d || ( ...
这里的主要考虑因素是什么?
最佳答案
第一次调用该函数时,它会创建一个新变量“d”并将其分配给自己。在 OOP 中,函数 withValue
就像一个类,而 d
就像一个静态成员。
console.log(withValue.d); //undefined
var x = withValue(5);
console.log(x.value); //5
console.log(withValue.d.value); //5
console.log(x === withValue.d); //true
变量x
和变量withValue.d
都是对同一个对象的引用:
withValue.d.value = 1;
console.log(x.value); //1
如果我再次调用 withValue
,它会回收或重用现有的静态成员 (withValue.d) 并更新它的值:
var y = withValue(8);
console.log(withValue.d.value, y.value, x.value); //8 8 8
console.log(x === y, x === withValue.d, y === withValue.d); //true true true
更新:如果 withValue
是:
function withValue(value) {
var d = {
enumerable: false,
writable: false,
configurable: false,
value: null
};
withValue.d = d;
d.value = value;
return d;
};
然后函数的每次调用都会创建一个新对象:
var x = withValue(1);
var y = withValue(2);
console.log(withValue.d.value, y.value, x.value); //2 2 1
console.log(x === y, x === withValue.d, y === withValue.d); //false false true
y.value = 999;
console.log(withValue.d.value, y.value, x.value); //999 999 1
现在创建了 2 个对象 - 一个由 y
和 withValue.d
引用,另一个由 x
引用。在第一种情况下,这三个变量访问同一个对象。
关于javascript - 这段代码中的 'recycling' 到底是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44473600/