2015-04-01 76 views
0

我有一个关于自定义函数的问题。自定义函数的属性在哪里?

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 

我在哪里可以得到'一切'属性?

+0

请注意,此处只创建一个实例,第二次调用* scareMe *将返回对第一次调用中创建的同一对象的引用(通过闭包到*实例*),所以* un1 *和* un2 *引用同一个对象,因此为什么'un1 === un2'是真的。 – RobG 2015-04-01 05:57:43

回答

2

它不会工作,因为一旦scareMe叫,你要重写scareMe另一个功能,当您尝试实际上改变的是第二种方法的原型不是第方法的初始调用后更改原型与您创建了该实例。所以原型的更改不会反映在您的实例中。


一种可能的解决方案是覆盖第二物体的原型与第一个

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