【问题标题】:How to check inheritance (object/prototype of)如何检查继承(对象/原型)
【发布时间】:2012-07-14 13:53:21
【问题描述】:

我想检查一个对象是否扩展了另一个对象(真,假):

例子:

var BaseObject = function(object) {
    this.name = object.name;
    this.someFunction = object.someFunction;
    this.someOtherProperty = object.someOtherProperty;
};

var ExtendingObject = new BaseObject({
    name: "extention",
    someFunction: function(value) { return value; },
    someOtherProperty = "hi"
});

// some possible function
var extends = isExtending(BaseObject, ExtendingObject);
var isParentof = isParentOf(BaseObject, ExtendingObject);

underscore.js 是否提供了这样的功能(我没找到...)?

如何进行这样的检查?

【问题讨论】:

标签: javascript underscore.js


【解决方案1】:

尝试使用instanceof 运算符。

【讨论】:

    【解决方案2】:

    ExtendingObject(顺便说一句,没有理由大写它 - 它不是一个类)并没有真正扩展传统意义上的基础对象 - 它只是实例化它。

    出于这个原因,正如@Inkbug 所说(+1),如果你想确保ExtendingObject 是基础对象的一个​​实例,你可以使用

    alert(ExtendingObject instanceof BaseObject); //true
    

    请注意,instanceof 只能回答“A 是 B 的实例”的问题 - 您不能问“A 的实例是什么?”。

    对于后者,您可以执行类似的操作(尽管我认为这不是跨浏览器)

    alert(ExtendingObject.constructor.name); //"BaseObject"
    

    【讨论】:

      【解决方案3】:

      我不了解 underscore.js,但 instanceof 可以满足您的需要。你可以这样使用它:

      function Unrelated() {}
      function Base( name, fn, prop ) {
         this.name = name;
         this.someFunction = fn;
         this.someProperty = prop;
      }
      function Extending( name, fn, prop, newProp ) {
         Base( name, fn, prop );
         this.newProperty = prop;
      }
      Extending.prototype = new Base();
      var a = new Extending( 'name', function () {}, 'prop', 'newProp' );
      

      现在你可以说:

      if( a instanceof Extending ) {/*it is true because a.prototype = Extending*/}
      if( a instanceof Base ) {/*it is true because a.prototype.prototype = Base*/}
      if( a instanceof Unrelated ) {/*it is false since Unrelated is not in prototype chain of a*/}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-07-27
        • 2012-06-19
        • 1970-01-01
        • 1970-01-01
        • 2012-01-10
        • 2011-03-06
        • 2014-11-26
        • 1970-01-01
        相关资源
        最近更新 更多