3

オブジェクトが別のオブジェクトを拡張するかどうかを確認したい (true、false):

例:

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 はそのような機能を提供していますか?

どうすればそのようなチェックを実行できますか?

4

3 に答える 3

6

instanceof演算子を使用してみてください。

于 2012-07-15T12:57:21.420 に答える
2

ExtendingObject(ちなみに、大文字にする理由はありません-クラスではありません)は、従来の意味で基本オブジェクトを実際に拡張していません-単にインスタンス化しているだけです。

このため、@Inkbug が (+1) と言うように、それExtendingObjectがベース オブジェクトのインスタンスであることを確認したい場合は、次を使用できます。

alert(ExtendingObject instanceof BaseObject); //true

は、「A は B のインスタンスですか」という質問にのみ答えることができることに注意してくださいinstanceof。「A は何のインスタンスですか?」という質問はできません。

後者の場合、次のようなことができます(ただし、これはクロスブラウザーではないと思います)

alert(ExtendingObject.constructor.name); //"BaseObject"
于 2012-07-15T13:09:17.703 に答える
1

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*/}
于 2012-07-15T13:12:08.340 に答える