[英]Setting prototype for Object Literal
假设我有以下代码;
var A = {a:10};
var B = {b:20};
B.prototype = A;
alert(B.a);
我对Ba的定义不明确。 难道我做错了什么? 如何设置对象文字的原型?
我知道如何为Constructor对象做。 所以下面的代码是完美的
function A(){this.a=10}
function B(){this.b=20}
B.prototype = new A();
b = new B;
alert(b.a);
我如何为对象文字做到这一点?
对象继承自构造函数的 prototype属性,而不是它们自己的属性。 构造函数的原型被分配给内部[[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
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
因此,普通对象没有原型。 作为构造函数的函数确实有原型。 这些原型用于填充使用每个构造创建的实例。
希望有帮助:)
仅当使用Function
对象时才使用原型,例如当您使用构造函数时。 但对于对象文字则不需要。
它们都是非常好的技术,所以它取决于你想在项目中做什么以及你正在使用或喜欢的JavaScript模式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.