js,使用函數過程中,寫不寫new的區別
2 回答
回首憶惘然
TA貢獻1847條經驗 獲得超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;}; |
區別是如果不new,直接調用YourFunc,不做對象的初始化;
如果new,先初始化一個對象,然后調用YourFunc作為初始化函數。
初始化對象的時候,會把所有YourFunc.prototype的屬性方法,copy一份給這個對象;意味著你在YourFunc里面如果調用this.a this.b this.c this.sayHello,都已經被初始化過
- 2 回答
- 0 關注
- 678 瀏覽
添加回答
舉報
0/150
提交
取消
