看jquery源代碼第一步的時(shí)候,對(duì)于jquery對(duì)象的創(chuàng)建就看的云里霧里,琢磨半天終于有點(diǎn)感覺(jué)了,在此記錄下
第一種方式:
var A = function(){return A.prototype.init();}A.prototype = {init:function(){this.age = 50;console.log(this);return this;},age:100}console.log(A() === new A());
1.分析下結(jié)果為什么為true
A()內(nèi)部調(diào)用的是A.prototype.init()函數(shù)
new A() 內(nèi)部會(huì)調(diào)用構(gòu)造函數(shù),而它的構(gòu)造函數(shù)就是function(){return A.prototype.init();},同樣調(diào)用的是A.prototype.init()函數(shù)
2.分析下A.prototype.init()函數(shù)返回什么
那就要看this了,判斷this指向誰(shuí),我們要在函數(shù)調(diào)用的時(shí)候分析,由于它是作為原型對(duì)象的屬性調(diào)用的,所以this就是原型對(duì)象A.prototype
這種創(chuàng)建方式,無(wú)論你調(diào)用多少次A(),他們其實(shí)都是返回的同一個(gè)對(duì)象,所以對(duì)b對(duì)象的修改會(huì)影響a對(duì)象,見(jiàn)下圖
var a = A();var b = A();console.log(a.age);console.log(b.age);b.age = 22;console.log(a.age);console.log(b.age);
那么如何解決這種問(wèn)題呢,接下來(lái)就講下第二種方式,它也是jquery采用的方式
第二種方式
var A = function(){return new A.prototype.init();//①}A.prototype = {init:function(){this.age = 50;console.log(this);return this;},age:100}
A.prototype.init.prototype = A.prototype;//②var a = new A();var b = new A();console.log(a===b);console.log(a.age);console.log(b.age);b.age = 22;console.log(a.age);console.log(b.age);
分析下①和②
①中new A.prototype.init()主要做了三件事
創(chuàng)建一個(gè)空對(duì)象var obj = {};
obj對(duì)象屬性_proto_指向函數(shù)A.prototype.init的prototype;
將A.prototype.init函數(shù)的this替換成obj對(duì)象,在調(diào)用A.prototype.init函數(shù),A.prototype.init.call(obj),并返回新對(duì)象
因?yàn)棰俜祷氐膶?duì)象的原型是A.prototype.init.prototype,它和A.prototype并沒(méi)什么關(guān)系,為了使新返回的對(duì)象可以繼承自A.prototype,所以②讓A.prototype.init.prototype指向A.prototype
所以方式二即創(chuàng)建了實(shí)例,又保證了各自的作用域獨(dú)立。
以上所述是小編給大家介紹的Javascript的無(wú)new構(gòu)建實(shí)例詳解,希望對(duì)大家以上幫助,如果大家想了解更多資訊,敬請(qǐng)關(guān)注武林網(wǎng)網(wǎng)站!
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注