2013-03-18 68 views
2

假設我有以下代碼;設置對象文字的原型

var A = {a:10}; 
var B = {b:20}; 
B.prototype = A; 
alert(B.a); 

我的B.a越來越不確定。 我做錯了什麼?如何設置對象字面值的原型?

我知道如何爲構造函數對象。所以下面的代碼工作完美

function A(){this.a=10} 
function B(){this.b=20} 
B.prototype = new A(); 
b = new B; 
alert(b.a); 

我該如何做對象文字?

+0

相關:http://stackoverflow.com/q/ 7015693/989121 – georg 2013-03-18 07:58:38

+0

簡短回答:你不能 – slebetman 2013-03-18 08:35:09

+0

可能的重複e的http://stackoverflow.com/questions/9959727/java-script-what-is-the-difference-between-proto-and-prototype或http://stackoverflow.com/questions/572897/how-does- javascript-prototype-work?lq = 1或http://stackoverflow.com/questions/650764/how-does-proto-differ-from-constructor-prototype?rq=1或http://stackoverflow.com/questions/ 9451881/prototype-vs-prototype-what-is-the-difference-mycons-proto-myco/9451979#9451979 – 2013-03-18 08:56:35

回答

3

原型屬性通常出現在Function對象中。這個原型應該是一個對象,並且該對象用於定義用構造函數創建的對象的屬性。

// Plain object, no prototype property here. 
var plainObject = {one: 1, two: 2}; 

// Constructor, a prototype property will be created by default 
var someConstruct = function() { 

    // Constructor property 
    someConstruct.constructProp = "Some value"; 

    // Constructor's prototype method 
    someConstruct.prototype.hello = function() { 
    return "Hello world!"; 
    } 
}; 

// Another constructor's prototype method 
someConstruct.prototype.usefulMethod = function() { 
    return "Useful string"; 
} 

var someInstance = new someConstruct(); 
console.log(someInstance.hello()); // => Hello world! 
console.log(someInstance.usefulMethod()); // => Useful string 

console.log(someConstruct.constructProp); // => Some value 
console.log(someConstruct.prototype); // => {usefulMethod: function, hello: function} 

console.log(plainObject.prototype); // => undefined 

所以,普通物體沒有原型。 作爲構造函數的函數確實有原型。這些原型用於填充每個構造創建的實例。

希望幫助:)

+1

定義屬性的區別是什麼?直接在原型上對Vs進行定義......就像在上述情況下someConstruct。 constructProp Vs someConstruct.prototype.somePrototypeProperty – testndtv 2013-03-18 09:12:19

0

使用Function對象只有當該原型中使用,例如當你使用一個構造函數。但對象文字不需要這樣做。

它們都是非常好的技術,所以它取決於你想要在項目中做什麼以及你正在使用的JavaScript模式或類似模式。

10

對象從它們的繼承構造函數的原型屬性,而不是它們自己的。構造函數的原型被分配給內部[[Prototype]]屬性,該屬性在某些瀏覽器中可用作__proto__屬性。

因此,對於b繼承自a,您需要將a放在b的繼承鏈上,例如,

經典原型繼承:

var a = {a: 'a'}; 
function B(){} 
B.prototype = a; 

var b = new B(); 
alert(b.a); // a 

使用ES5的Object.create:

var a = {a: 'a'}; 
var b = Object.create(a); 

alert(b.a); // a 

使用Mozilla __proto__

var a = {a: 'a'}; 
var b = {}; 
b.__proto__ = a; 

alert(b.a); // a 
+0

看一下ES5的Object.create例子,如果'a'位於'b'的繼承/原型鏈中,那麼如何擴充'a'? – 2013-08-15 22:17:29

+0

'a'的屬性需要直接增加,例如'a.foo ='foo''。即使「a」上存在相同名稱的屬性,分配給「b」也會創建「b」屬性。 – RobG 2014-06-09 22:58:55

+0

@RobG可能會改寫爲「賦予'b'將在'b''上創建一個屬性而不是''b'的屬性」。 – cchamberlain 2016-08-29 00:48:49