Setting prototype for Object Literal

邮差的信 提交于 2019-11-27 16:58:06

问题


Let's say I have the following code;

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

I am getting undefined for B.a . Am I doing something wrong? How do I set the prototype for object literal ?

I know how to do for Constructor object. So the following code works perfect

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

How do I do it for object literal ?


回答1:


Objects inherit from their constructor's prototype property, not their own. The constructor's prototype is assigned to the internal [[Prototype]] property that is available in some browsers as the __proto__ property.

So for b to inherit from a, you need to put a on b's inheritance chain, e.g.

Classic prototype inheritance:

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

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

Using ES5 Object.create:

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

alert(b.a); // a

Using Mozilla __proto__:

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

alert(b.a); // a



回答2:


The prototype property is usually present in a Function object. This prototype should be an object, and this object is used to define the properties of an object created with a constructor.

// 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

So, plain objects have no prototypes. Functions which work as constructors do have prototypes. These prototypes are used to fill an instance created with each construct.

Hope that helps :)




回答3:


Only when using Function object that prototype is used, e.g. when you use a constructor. But no need of that for object literals.

Both of them are very good techniques, so it depends on what you want to do in a project and the JavaScript pattern you are using or like.



来源:https://stackoverflow.com/questions/15472005/setting-prototype-for-object-literal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!