2013-03-18 119 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