有人可以解释为什么我们有这种行为?据我所知,它应该像这样,但我无法解释Js继承和instanceof
function foo() {}
function foo1() {}
foo.prototype = foo1.prototype = {};
var _foo = new foo();
alert(_foo instanceof foo1); // true
有人可以解释为什么我们有这种行为?据我所知,它应该像这样,但我无法解释Js继承和instanceof
function foo() {}
function foo1() {}
foo.prototype = foo1.prototype = {};
var _foo = new foo();
alert(_foo instanceof foo1); // true
在JavaScript中,使用对象。
我认为这是比较容易理解,如果你比较这对更熟悉的物体
//defines a "class" Person
function Person() {}
//defines a "class" Animal
function Animal() {}
变化Animal
和Person
原型
Person.prototype = Animal.prototype = {};
原型可以用来扩展“类”,例如
function Person(name){
this.name=name;
}
Person.prototype.nameInUperCase=function(){
return this.name.toUpperCase();
}
实例化
var myPerson = new Person();
检查我的人是否是实例。
// true because you instantiate the same prototype
// remember Person.prototype = Animal.prototype = {};
alert(myPerson instanceof Animal);
的instanceof
运营商检查是否左边的操作数是在其原型链的原型对象的对象右手操作数。由于你的两个函数共享同一个原型对象,所以一个实例被视为另一个的实例。
o instanceof f
检查f.prototype
引用的对象是否出现在原型链o
的任何地方。在你的情况下,因为foo.prototype
和foo1.prototype
都涉及同一个对象,所以通过new foo
或new foo1
创建的任何对象都将为instanceof
foo
和foo1
。
这是覆盖在规范的以下部分:Runtime Semantics: InstanceofOperator(O, C),Function.prototype[@@hasInstance] (V)和OrdinaryHasInstance (C, O),大部分工作在最后一个环节正在做,步骤4到7(7具有通过o
的原型为循环分步骤链)。