Setting prototype for Object Literal

给你一囗甜甜゛ 提交于 2019-11-29 05:20:33

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

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 :)

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.

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