2012-06-07 61 views
3

據我所知,「__proto__是一個對象的內部屬性,指向其原型」,所以在下面的例子中,我認爲c2.prototype將等於c2.__proto__。爲什麼他們不具有相同的價值?爲什麼在這個例子中沒有.__ proto__ = .prototype?

<!DOCTYPE html> 
<html> 
    <head> 
     <script type="text/javascript"> 
      window.onload = function() { 
       var Circle = function(radius) { 
        this.radius = radius; 
        this.doubleRadius = function() { 
         return this.radius * 2; 
        } 
       } 

       var c1 = new Circle(4); 

       Circle.prototype.area = function() { 
        return Math.PI*this.radius*this.radius; 
       } 

       var c2 = new Circle(5); 

       console.log('--- first circle object, created before adding "area" method'); 
       console.log(c1.radius); 
       console.log(c1.doubleRadius()); 
       console.log(c1.area()); 

       console.log('--- second circle object, created after adding "area" method'); 
       console.log(c2.radius); 
       console.log(c2.doubleRadius()); 
       console.log(c2.area()); 

       console.log(c2.prototype); // undefined 
       console.log(c2.__proto__); // Object { area=function() } 

      } 
     </script> 
    </head> 
<body> 
</body> 
</html> 

回答

1

請嘗試以下操作。

console.log(c2.constructor.prototype); 
console.log(c2.__proto__); 

Acturly,.__proto__ == .constructor.prototype當C2是一個對象。

+1

請參閱我對工程師的答案的評論,如果這不是事實。 http://jsfiddle.net/mendesjuan/UrqmL/ –

2

obj.__proto__obj.constructor.prototype短版,不obj.prototype

console.log(c2.constructor.prototype === c2.__proto__); //true 
console.log(c2.prototype === c2.__proto__); //false 
+1

這不完全是一個簡短的版本。您可以更改對象的單個實例的原型,而不會影響其他實例。確實,兩個版本都指向相同的對象(除非你已經修改過它)。 –

+0

@JuanMendes'改變單個實例的原型'是什麼意思?請給我看一個例子,其中'c2.constructor.prototype!= c2 .__ proto__'。 – Engineer

+0

我的評論說,除非你修改了它,否則我覺得這聽起來很明顯。這是http://jsfiddle.net/mendesjuan/UrqmL/我從同一個構造函數創建了兩個實例,修改了其中一個構造函數的'__proto__'屬性。對於被修改的那個,'console.log(a.constructor.prototype == a .__ proto __);'輸出false –

3

簡單的答案是,c2.constructor.prototype == c2.__proto__

構造有.prototype財產。實例沒有,但他們確實有.__proto__.constructor屬性

相關問題