亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

javascript - Doubts about singleton mode in js
怪我咯
怪我咯 2017-06-30 09:58:37
0
6
782

The following code

function Universe() {

    // 緩存的實例
    var instance = this;

    // 其它內容
    this.start_time = 0;
    this.bang = "Big";

    // 重寫構造函數(shù)
    Universe = function () {
        return instance;
    };
}

// 測試
var uni = new Universe();
var uni2 = new Universe();
uni.bang = "123";
console.log(uni === uni2); // true
console.log(uni2.bang); // 123

Click to view the original text

question:

new Universe()的過程是:
var o = {};
Universe.call(o);//這一步是將Universe中this對應的屬性賦值給o;
o.__proto__ = Universe.prototype;//將Universe原型上的方法賦值到o的__proto__屬性上;

Then var instance = this;, does this refer to a different object o? So after rewriting the constructor, isn't the returned instance a different object? Why are they equal in the end

怪我咯
怪我咯

走同樣的路,發(fā)現(xiàn)不同的人生

reply all(6)
某草草

Because after rewriting the constructor, an object is returned. This object will overwrite the object you generated with the new constructor. I don’t know if I made it clear

扔個三星炸死你

@mpccc is right.

If the constructor returns an object, then the new object will be the object.

You can take a look at the constructor section in Secret Garden

過去多啦不再A夢

I’m a newbie too, so I’ll try to answer it, don’t blame me if I’m wrong

First, does this refer to different objects? When the constructor is called for the first time, an empty object is generated and this inside the function points to the empty object. Then the code is executed, and finally the object is returned, which is
uni .

In the second call, due to the rewriting of the first function, a closure was generated. The internal instance of this closure just pointed to the object generated in the first call

uni. When the second call When you execute new Universe(), you are executing a closure, which will also generate an empty object, but that object does not use it. Instead, it directly returns the instance inside the closure, which is uni.

So

uni2 === uni.

迷茫

Another question, writing a singleton pattern like this is a bit redundant. To create a unique objectyou don’t have to create a constructor

var single = function(fn){ 
 var instance; 
 return function(){ 
     return instance || (instance = fn .apply(this, arguments)); 
 } 
}; 
ringa_lee

Didn’t you write the comments and rewrite the constructor? After you create new once, you will no longer have the line of code var instance = this;, and the instance will naturally remain unchanged

//簡單打印一下就知道了
console.log(Universe)
var uni = new Universe()
console.log(Universe)
阿神

When new Universe() is executed for the first time, a new this is indeed generated, and the Universe constructor is rewritten. When this new Universe() is called again later, it will only return instance, no new objects will be generated.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template