JavaScript 原型仅限于函数? [英] JavaScript prototype limited to functions?

查看:31
本文介绍了JavaScript 原型仅限于函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

o.prototype = {...}仅当 o 是函数时才有效.假设我有以下代码

o.prototype = {...} is working only if o is a Function. Suppose I've the following Code

 conf = {
  a: 2,
  b: 4
 };
 conf.prototype = {
  d: 16
 }

conf.aconf.b 没问题并返回正确的值.但是 conf.d 不返回 16 而是未定义.有没有什么解决方案让基于原型的泛化也可以应用于这些类型的对象.

conf.a and conf.b is OK and returns proper values. But conf.d doesn't return 16 rather it goes undefined. Is there any solution suck that prototype based generalization can also be applied on these type of Objects.

推荐答案

您混淆了可以在 构造函数内部 [[Prototype]] 属性.

You are confusing the prototype property that can be used on Constructor Functions and the internal [[Prototype]] property.

所有对象都有这个内部 [[Prototype]] 属性,只有 new 操作符当你用构造函数调用它时允许设置它(通过[[Construct]] 内部操作).

All objects have this internal [[Prototype]] property, and only the new operator when you call it with a constructor function is allowed to set it (through the [[Construct]] internal operation).

如果你想拥有对象实例的原型继承(不使用构造函数),Crockford 的 Object.create 技术就是您想要的(该方法现在是最近批准的 ECMAScript 第 5 版的一部分):

If you want to have prototypal inheritance with object instances (without using constructors), the Crockford's Object.create technique is what you want (that method is now part of the recently approved ECMAScript 5th Edition):

// Check if native implementation available
if (typeof Object.create !== 'function') {
  Object.create = function (o) {
    function F() {}  // empty constructor
    F.prototype = o; // set base object as prototype
    return new F();  // return empty object with right [[Prototype]]
  };
}

var confProto = {
  d: 16
};
var conf = Object.create(confProto);
conf.a = 2;
conf.b = 4;

在上面的代码中,conf 将有它的三个成员,但只有 ab 会实际存在于其上:

In the above code conf will have its three members, but only a and b will exists physically on it:

conf.hasOwnProperty('a'); // true 
conf.hasOwnProperty('b'); // true
conf.hasOwnProperty('d'); // false

因为 d 存在于 conf [[Prototype]] (confProto).

Because d exists on the conf [[Prototype]] (confProto).

属性访问器.[] 负责解析在原型链(通过 [[Get]] 内部方法).

The property accessors, . and [] are responsible to resolve the properties looking up if necessary in the prototype chain (through the [[Get]] internal method).

这篇关于JavaScript 原型仅限于函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆