2017-02-15 50 views
0

我已經谷歌搜索並檢查堆棧溢出的答案。但我無法清楚地瞭解這一點。任何人都可以幫忙簡單解釋下面的例子嗎?這個vs原型Javascript

function myObject(){ 
    this.iAm = 'an object'; 
    myObject.prototype.values = "value"; 
    this.whatAmI = function(){ 
     alert('I am ' + this.iAm); 
    } 
} 
var myObject1 = new myObject(); 
myObject1.values = "value2"; 
myObject1.iAm = "New"; 

alert(myObject1.values); 


var myObject2 = new myObject(); 
alert(myObject1.values); 

在上面的代碼,如果我用this.iAm,它的行爲以同樣的方式表現原型。

我是JavaScript面向對象編程的新手。

我預計會有很多倒票。但我並不擔心這一點,因爲我只想以清晰簡單的方式接收解釋,但我仍然能夠找到答案。

+0

我不明白那個傢伙.. :( –

+0

你的疑問是什麼?你試圖提醒'myObject1.values',它會返回myObject1上的'values'屬性。 – Agalo

+0

如何使用這個和原型不同? –

回答

1

我將嘗試猜測/解決您的實際問題。

請看下面的代碼片段:

function A() { 
    this.text = "hello"; 
} 

var a = new A(); 
a.text = "hello world"; 

其實這裏只有設置text屬性在構造函數中(即this.text)函數或一旦對象已經被創建(即a.text)之間的差異。基本上,構造函數中的this是正在創建的對象,而a變量是已創建的對象。

兩者的唯一區別在於,在調用構造函數期間創建的對象中定義的屬性將被創建給所有由整個構造函數所創建的對象。

現在請參見下面的代碼段也:

function A() {} 
A.prototype = { 
    text: "hello" 
}; 

var a1 = new A(); 
var a2 = new A(); 

// both will output "hello" 
console.log(a1.text); 
console.log(a2.text); 

A.prototype.value = "bye"; 

// both will output "bye" 
console.log(a1.text); 
console.log(a2.text); 

結論:在一個構造函數的原型定義的屬性通過共享相同的原型中的所有對象共享。因此,即使您使用構造函數創建對象,它們仍然存在。