【问题标题】:Setting prototype for Object Literal为 Object Literal 设置原型
【发布时间】:2013-03-06 12:07:13
【问题描述】:

假设我有以下代码;

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

对象字面量如何处理?

【问题讨论】:

标签: javascript prototype prototypal-inheritance


【解决方案1】:

原型属性通常存在于函数对象中。这个原型应该是一个对象,这个对象用来定义一个用构造函数创建的对象的属性。

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

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

希望有帮助:)

【讨论】:

  • 在原型上直接定义一个属性有什么区别......就像上面的例子 someConstruct.constructProp Vs someConstruct.prototype.somePrototypeProperty
【解决方案2】:

只有在使用 Function 对象时才会使用原型,例如当您使用构造函数时。但对象字面量就不需要了。

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

【讨论】:

    【解决方案3】:

    对象继承自其构造函数的原型属性,而不是它们自己的。构造函数的原型分配给内部的[[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
    

    【讨论】:

    • 看看 ES5 Object.create 示例,一旦 ab 的继承/原型链上,您将如何扩充 a
    • a 的属性需要直接扩充,例如a.foo = 'foo'。分配给b 将创建b 的属性,即使a 上存在同名属性。
    • @RobG 可能会将其改写为“分配给b 将在b 上创建一个属性”,而不是“b 的属性”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多