Skip to content

[javascript] 函式建構(function constructor),new 關鍵字的用法與解析

Published: at 03:19 AM

在 javascript 中,有一個關鍵字為 new

它可以幫我們透過函式建構(function constructor)一個物件,並賦予相關的屬性及方法。

我們直接來看程式碼範例吧~

[javascript] function hello() { console.log(“Hello World!”); } var a=new hello(); console.log(a); // hello{} [/javascript]

上面這段程式碼,透過 new 會幫我們創造一個空的物件

接下來我們看一些賦予屬性與方法的例子 PS. 以下的 this.fullName 方法並不適合這樣寫,詳細請見https://wp.me/p7kqsB-bz

[javascript] function person() { this.firstName=“camel”; this.lastName=“chang”; this.fullName=function(){ console.log(this.firstName+” “+this.lastName); }; } var a=new person(); console.log(a); // person{firstName: “camel”, lastName: “chang”, fullName: function()} [/javascript]

這樣原本空的物件,就會被賦予相關屬性與方法,有點像 C++ 或 JAVA 中的 class。

再來,我們看看若我們宣告的函式有相關回傳值的話呢?

[javascript] function person() { this.firstName=“camel”; this.lastName=“chang”; this.fullName=function(){ console.log(this.firstName+” “+this.lastName); }; return “ok”; } var a=new person(); console.log(a); // person{firstName: “camel”, lastName: “chang”, fullName: function()} [/javascript]

最後,若我們嘗試回傳一個物件呢?

[javascript] function person() { this.firstName=“camel”; this.lastName=“chang”; this.fullName=function(){ console.log(this.firstName+” “+this.lastName); }; return {“success”:1}; } var a=new person(); console.log(a); // Object{success:1} [/javascript]

可以看到,若我們回傳物件的話,將會以回傳的物件為主,原有的物件屬性與方法將不會回傳。

參考資料:

https://pjchender.blogspot.tw/2016/06/javascriptfunction-constructornew.html