使用原型函数名称而不是其属性的对象 [英] Object Using name of prototype function name instead of its property

查看:43
本文介绍了使用原型函数名称而不是其属性的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了两个函数A和B.将A作为B的原型. jsfiddle

I created two function A and B. Made A as prototype of B. jsfiddle

function A(){

}

function  B(){
    this.name ="Class B";
}

B.prototype = A;
var b = new B();
alert(b.name); // expected Class B got A

我知道我应该使用 B.prototype = new A();

是否期望上述行为?在上述情况下,能否获得"Class B"而不是"A"?

Is above behavior expected? Is it possible to get "Class B" instead of "A" in above scenario?

注意:我在上面使用的是因为A具有与之关联的一些属性,如 A.text ="Text" A.text1 ="Text2" ,并且我希望这些属性可用于B.因此,不能使用 B.prototype == A.prototype..

Note: I am using above because A has some property associated with it as A.text = "Text" A.text1 = "Text2" and I want these property available to B. so B.prototype == A.prototype. can not be used.

推荐答案

看看可能的重复使用的原因是什么?在'Derived.prototype = new Base 以及此答案上的'new'关键字,说明为什么没有javascript中的类".

Have a look at the possible duplicate What is the reason to use the 'new' keyword at Derived.prototype = new Base and also at this answer on why there are no "classes" in javascript.

是的,此行为是预期的. B.prototype 是您的 b 实例所继承的对象,是功能对象 A .因此,它确实继承了 name 属性,它是字符串"A" .

Yes, the behaviour is expected. B.prototype, the object from which your b instance inherits, is the function object A. So, it does inherit its name property which is the string "A".

而且,此属性是不可变的(它的属性描述符为 {configurable:false,可枚举:false,值:"B",可写:false} ),因此,当您尝试分配新的值为 b.name 这将检查是否为 [[CanPut]] 会返回 false -没有任何反应.在严格模式下,会抛出在严格模式下无效的分配 TypeError(演示).

And, this property is immutable (its property descriptor is {configurable: false, enumerable: false, value: "B", writable: false}), so when you try to assign a new value to b.name, this will check for [[CanPut]] which returns false - and nothing happens. in strict mode, an Invalid assignment in strict mode TypeError would be thrown (demo).

您只能使用 Object.defineProperty .

You only could overwrite it using Object.defineProperty.

@Edit:我不确定为什么要让这些属性由 B 继承.它们是 A 构造函数的静态属性",应保留在此处.当前,除了 Function.prototype 之外,没有其他方法可以让Function继承任何东西,因此您可以复制它们,也可以不使用它们.告诉我们您需要它们的内容,我们可以找到解决方案.

@ I'm not sure why you want those properties inherited by B. They are "static attributes" of the A constructor function and they should stay there. There is currently no way to let a Function inherit from anything else than Function.prototype, so either you go with copying them or your don't use them. Tell us for what you'd need them, and we can find a solution.

更改函数(和一般对象)的 prototype 属性不会使它们碰巧继承自其他任何东西.函数的 prototype 属性指向新创建(构造的)实例将从其继承的对象.

Changing the prototype property of functions (and objects in general) does not make them happen to inherit from anything else. The prototype property of functions points to the object from which newly created (constructed) instances will inherit.

这篇关于使用原型函数名称而不是其属性的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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