`constructor` 属性的真正用途是什么? [英] What is the `constructor` property really used for?

查看:31
本文介绍了`constructor` 属性的真正用途是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 JavaScript 中,每个函数的原型对象都有一个不可枚举的属性 constructor 指向函数 (EcmaScript §13.2).它不用于任何本机功能(例如 instanceof 仅检查原型链),但是我们鼓励在覆盖函数的 prototype 属性以进行继承时调整它:

In JavaScript, every function's prototype object has a non-enumerable property constructor which points to the function (EcmaScript §13.2). It is not used in any native functionality (e.g. instanceof checks only the prototype chain), however we are encouraged to adjust it when overwriting the prototype property of a function for inheritance:

SubClass.prototype = Object.create(SuperClass.prototype, {
    constructor: {value:SubClass, writable:true, configurable:true}
});

但是,我们(包括我)这样做只是为了清晰和整洁吗?是否有任何实际用例依赖于 constructor 属性?

But, do we (including me) do that only for clarity and neatness? Are there any real-world use cases that rely on the constructor property?

推荐答案

我真的不明白为什么 constructor 属性是它在 JS 中的样子.我偶尔会发现自己使用它来获取 IE 中对象的原型(例如 Event 对象)<9. 但是我确实认为它允许一些 ppl 模仿经典的面向对象编程结构:

I can't really see why the constructor property is what it is in JS. I occasionally find myself using it to get to the prototypes of objects (like the Event object) in IE < 9. However I do think it's there to allow some ppl to mimic classical OO programming constructs:

function Foo()
{
    this.name = 'Foo';
}
function Bar()
{
    this.name = 'Bar';
}
function Foobar(){};
Foo.prototype = new Foobar;
Foo.prototype.constructor = Foo;
Bar.prototype = new Foobar;
Bar.prototype.constructor = Bar;
var foo = new Foo();
var bar = new Bar();
//so far the set-up
function pseudoOverload(obj)
{
    if (!(obj instanceof Foobar))
    {
        throw new Error 'I only take subclasses of Foobar';
    }
    if (obj.constructor.name === 'Foo')
    {
        return new obj.constructor;//reference to constructor is quite handy
    }
    //do stuff with Bar instance
}

所以AFAIK,构造函数属性的优点"是:

So AFAIK, the "advantages" of the constructor property are:

  • 从实例轻松实例化新对象
  • 能够将您的对象分组作为某个类的子类,但仍然能够检查您正在处理的特定类型的子类.
  • 如您所说:保持整洁.
  • instantiating new objects from instance easily
  • being able to group your objects as being subclasses of a certain class, but still being able to check what particular type of subclass you're dealing with.
  • As you say: being tidy.

这篇关于`constructor` 属性的真正用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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