设置Object Literal的原型

时间:2013-03-18 07:54:58

标签: javascript prototype prototypal-inheritance

假设我有以下代码;

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

我对B.a的定义不明确。 难道我做错了什么?如何设置对象文字的原型?

我知道如何为Constructor对象做。所以下面的代码完美无缺

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

我如何为对象文字做到这一点?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:3)

prototype属性通常存在于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

因此,普通对象没有原型。 作为构造函数的函数确实有原型。这些原型用于填充使用每个构造创建的实例。

希望有所帮助:)

答案 2 :(得分:0)

仅在使用Function对象时才使用原型,例如当你使用构造函数。但对于对象文字则不需要。

它们都是非常好的技术,所以它取决于你想在项目中做什么以及你正在使用或喜欢的JavaScript模式。

相关问题