将this.constructor与构造函数调用一起使用以访问静态属性时是否存在兼容性问题



我想在初始化期间使用构造函数的静态属性,例如:

var MyConstructor = function() {
  this.foo = 'foo';
  this.set_bar();
}
MyConstructor.bar = "bar";
MyConstructor.prototype = {
  set_bar: function() {
    this.bar = this.constructor.bar;
  }
}
var myObj = new MyConstructor();

这在新浏览器中似乎很好用,但在旧浏览器中会失败吗?我一直在谷歌上找不到这个。我想知道是否有些浏览器在构造后设置了this.constructor,从而使该属性在构造过程中不可用。

没有设置属性,它们是在对象上查找的。如果属性不在对象上,则会在对象的原型对象上查找它。如果它不在对象的原型对象上,它会在对象的原型机对象的原图对象上查找,依此类推

您的代码无法按预期工作,因为MyConstructor.prototype =覆盖了具有正确构造函数的默认原型对象。因此MyConstructor.prototype不具有constructor属性,myObj也不具有。所以this.constructor === Object,而不是MyConstructorObject.barundefined,因此myObj.bar也是。

修复方法是扩展默认原型而不是覆盖,或者重新插入构造函数:

MyConstructor.prototype = {
    set_bar: function() {
        this.bar = this.constructor.bar;
    },
    constructor: MyConstructor
}

最新更新