鍍金池/ 問(wèn)答/HTML/ 立即執(zhí)行函數(shù)為什么會(huì)影響構(gòu)造函數(shù)的原型鏈

立即執(zhí)行函數(shù)為什么會(huì)影響構(gòu)造函數(shù)的原型鏈

我在寫(xiě)代碼的時(shí)候遇見(jiàn)這個(gè)問(wèn)題,代碼如下:

function test(){
    
}
test.prototype.name = function(){
    console.log("test_prototype");
}
(function(){
    console.log("立即執(zhí)行函數(shù)");
})()

clipboard.png

請(qǐng)問(wèn),為什么連帶test的prototype一起執(zhí)行了?
希望大神指點(diǎn)下。多謝。

回答
編輯回答
夢(mèng)一場(chǎng)

加分號(hào)啊。老生常談了。

function test(){
    
}
test.prototype = function(){
    console.log("test_prototype");
}; //這里加分號(hào),否則就連成一條語(yǔ)句執(zhí)行了
(function(){
    console.log("立即執(zhí)行函數(shù)");
})()

// 不加分號(hào),瀏覽器就是這樣認(rèn)為的:

test.prototype = (function(){
    console.log("test_prototype");
})(function(){
    console.log("立即執(zhí)行函數(shù)");
})()

// 也就是這樣的:
f1 = function(){
    console.log("test_prototype");
};
f2 = function(){
    console.log("立即執(zhí)行函數(shù)");
};
test.prototype = f1(f2)()
2017年4月21日 19:13
編輯回答
尤禮

我笑笑不說(shuō)話 =.=

2018年4月7日 15:06
編輯回答
尋仙

給了像我這種不加分號(hào)黨敲了個(gè)警鐘。然后發(fā)現(xiàn)還好,箭頭函數(shù)不會(huì)有這種影響,不知道還有沒(méi)有奇怪的特例。。。

2018年3月29日 22:21
編輯回答
別逞強(qiáng)

語(yǔ)法錯(cuò)誤。一般為了防止別人代碼末尾沒(méi)有加分號(hào)。都會(huì)在立即執(zhí)行函數(shù)前加上;。這樣比較保險(xiǎn)

;(function () {
    // your code
})();
2018年6月17日 15:38