2017-09-13 86 views
-2

我正在學習JavaScript,我只是想出了這個想法爲什麼我需要'新'來創建一個對象?

爲什麼我需要'新'來創建一個對象?

function a(){}; 
var b = new a(); 
var c = {}; 
c.__proto__ = a.prototype; 

如果我創建一個對象,並指出這是__proto__到構造函數的原型。 與使用new創建對象的方法相同嗎?

+1

您的代碼是無效的。 –

+0

第一行應該是** function a(){}; ** –

+0

對不起,我剛編輯它。 – franose

回答

0

在你的場景中,它們將是等效的(儘管__proto__由於未被正確標準化而歷來不受歡迎),但僅僅是因爲a的定義爲空。

如果a會執行一些初始化,則不會爲c完成。

至於爲什麼new是必要的,叫a()new a()之間的區別是上下文對象(this將是全局對象或新創建的對象)。

0

原則上,你不需要需要什麼。 Javascript的創建對象略有不同,當然這些對象的工作方式稍有不同。在你的例子:

function a() = {}; // syntax error, correct syntax is function a() {} 
var b = new a(); // creates a new instance of a - assuming a is a constructor function 
var c = {}; // creates a new object literal 
c.__proto__ = a.prototype // assings the prototype of function a to __proto__ of c 

根據經驗的基本規則,如果你只是想創建一個對象使用對象字面方式。如果你想使用構造函數模式,你想使用new關鍵字來使用構造函數創建實例 - 你也可以手動創建實例,但new是語法糖。我會盡量避免直接將對象分配給__proto__,因爲這通常是在內部完成的。另一種基於其他對象創建對象的方法是使用Object.create({})

最新的ES語法引入了class關鍵字來抽象出構造函數模式。這是該語言的一個極端特徵。閱讀更多here

希望它有幫助,快樂的學習!

+0

對不起,語法error.Thanks你的答案,它有很大的幫助! – franose

0

首先,__proto__僅支持safari,chrome,firefox,IE不支持,並且尚未成爲標準。

function Animal(name) { 
    this.name = name; 
} 

Animal.prototype.run = function() { 
    console.log(this.name + 'can run...'); 
} 

var cat = new Animal('cat'); 

到模擬new過程如下:

//Simulation process 
new Animal('cat')=function(){ 
    let obj={}; //create an empty object 
    obj.__proto__=Animal.prototype; 
    //obj->Animal.prototype->Object.prototype->null 
    return Animal.call(obj,'cat');// bind this to the instantiated object 
} 
+0

謝謝!所以真正的'new'模擬更加複雜,因爲真正的構造函數不是空的。關鍵字'new'有助於簡化流程? – franose

+0

是的,快點吧 – Alvin

相關問題