10
09/2014
javascript instanceof
对我这样的伪程序员来说,对象、实例和继承,理解还是不够。
The instanceof operator tests whether an object has in its prototype chain the prototype property of a constructor.
有说法云:看 左边 是否是 右边 的一个事例(好像是废话? a instance of b)
function C(){} // defining a constructor function D(){} // defining another constructor var o = new C(); o instanceof C; // true, because: Object.getPrototypeOf(o) === C.prototype o instanceof D; // false, because D.prototype is nowhere in o's prototype chain o instanceof Object; // true, because: C.prototype instanceof Object // true C.prototype = {}; var o2 = new C(); o2 instanceof C; // true o instanceof C; // false, because C.prototype is nowhere in o's prototype chain anymore D.prototype = new C(); // use inheritance var o3 = new D(); o3 instanceof D; // true o3 instanceof C; // true
[] instanceof window.Array //true [] instanceof window.frames[0].Array //false
Chrome 控制台
function Car(make, model, year) { this.make = make; this.model = model; this.year = year; } qingCar=new Car('chevolete','aveo','2008') Car {make: "chevolete", model: "aveo", year: "2008"} k=Car(1,2,3) undefined qingCar.price='88000' "88000" qingCar Car {make: "chevolete", model: "aveo", year: "2008", price: "88000"} a=new Car(1,2,3) Car {make: 1, model: 2, year: 3} b=new Car(1,2,3) Car {make: 1, model: 2, year: 3} a==b false
似乎有点类,事例,(打酱油),特有属性的意思了。