JavaScript原型仅限于功能? [英] JavaScript prototype limited to functions?

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

问题描述

o.prototype = {...}只有当o是一个Function时,
才有效。
假设我有下面的代码:

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

conf.a conf.b 即可,并返回适当的值。但是 conf.d 不返回16,而是未定义。是否有任何解决方案吸引基于原型的泛化也可以应用于这些类型的对象。

解决方案

c $ c> prototype 可用于构造函数的属性功能内部 [[Prototype]] 属性。



所有对象都具有此内部 [[Prototype]] 属性,并且只有 new 运算符当您使用构造函数调用它时,可以设置它(通过 [[Construct]] 内部操作)。



如果你想用对象实例(不使用构造函数)进行原型继承,Crockford的
$ $ p $ //检查本地实现是否可用
if(typeof Object.create!== 'function'){
Object.create = function(o){
function F(){} //空构造函数
F.prototype = o; //将基础对象设置为原型
return new F(); //返回右对象[[Prototype]]
};
}

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

在上面的代码中, conf 三位成员,但只有 a b 会在身体上存在:

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

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

资源访问器。 code>和 [] 负责解析在原型链中查找的属性(通过 [[Get]] 内部方法)。


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

解决方案

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

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

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;

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

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

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天全站免登陆