js,使用函數(shù)過程中,寫不寫new的區(qū)別
2 回答

炎炎設(shè)計(jì)
TA貢獻(xiàn)1808條經(jīng)驗(yàn) 獲得超4個贊

回首憶惘然
TA貢獻(xiàn)1847條經(jīng)驗(yàn) 獲得超11個贊
123456789101112131415161718 | function YourFunc(){ // beginning of YourFunc'code if ( this instanceof YourFunc){ document.title = "You called [YourFunc] as Class's constructor" ; this .sayHello(); } else { document.title = "You called [YourFunc] as just a Function" ; } // ending of YourFunc's code } YourFunc.prototype={ a : 0, b : [], c :{} }; YourFunc.prototype.sayHello= function (){ document.title = "hello" + document.title; }; |
區(qū)別是如果不new,直接調(diào)用YourFunc,不做對象的初始化;
如果new,先初始化一個對象,然后調(diào)用YourFunc作為初始化函數(shù)。
初始化對象的時候,會把所有YourFunc.prototype的屬性方法,copy一份給這個對象;意味著你在YourFunc里面如果調(diào)用this.a this.b this.c this.sayHello,都已經(jīng)被初始化過
- 2 回答
- 0 關(guān)注
- 661 瀏覽
添加回答
舉報
0/150
提交
取消