我有一个关于自定义函数的问题。
var scareMe = function(){
console.log("Boo!");
var instance = this;
scareMe = function(){
console.log("Double Boo!");
return instance;
}
}
scareMe.prototype.nothing = true;
var un1 = new scareMe();
console.log(un1.nothing); //true
scareMe.prototype.everything = true;
var un2 = new scareMe();
console.log(un1 === un2); //true
它按我的预期工作。
console.log(un2.everything); //undefined
我在哪里可以获得“一切”属性?
最佳答案
它不会工作,因为一旦调用 scareMe
,当您在实际更改的初始调用后尝试更改原型(prototype)时,就会用另一个函数覆盖 scareMe
第二个方法的原型(prototype),而不是您创建实例所用的第一个方法。因此对原型(prototype)的更改不会反射(reflect)在您的实例中。
一种可能的解决方案是用第一个对象覆盖第二个对象的原型(prototype)
var scareMe = function () {
console.log("Boo!");
var instance = this,
proto = scareMe.prototype;
scareMe = function () {
console.log("Double Boo!");
return instance;
}
scareMe.prototype = proto;
}
scareMe.prototype.nothing = true;
var un1 = new scareMe();
console.log('nothing', un1.nothing); //true
scareMe.prototype.everything = true;
var un2 = new scareMe();
console.log(un1 === un2); //true
console.log('everything', un1.everything); //true
演示:Fiddle
<小时/>另一种写法可能类似于
var scareMe = (function () {
var instance;
return function () {
if (instance) {
return instance;
}
instance = this;
}
})();
演示:Fiddle
关于javascript - 自定义函数的属性在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29383632/