其中是自定义函数中的属性

Where is the property in self-defining function?

本文关键字:属性 自定义函数      更新时间:2023-09-26

我有一个关于自定义函数的问题。

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,当您在初始调用后尝试更改原型时,您将用另一个函数覆盖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