原型链
prototype
prototype 的验证几种方法
理解 prototype
http://www.ruanyifeng.com/blog/2010/05/object-oriented_javascript_encapsulation.html
理解 prototype
function Cat(name,color){
// 本地属性
this.name = name;
this.color = color;
}
// 继承属性
Cat.prototype.type = "猫科动物";
Cat.prototype.eat = function(){
alert("吃老鼠")
};
然后生成实例
var cat1 = new Cat("大毛","黄色");
var cat2 = new Cat("二毛","黑色");
alert(cat1.type); // 猫科动物
cat1.eat(); // 吃老鼠
这时所有实例的 type 属性和 eat() 方法, 其实都是同一个内存地址, 指向 prototype 对象, 因此就提高了运行效率.
alert(cat1.eat == cat2.eat); //true
prototype 的验证几种方法
1> isPrototypeOf()
这个方法用来判断, 某个 proptotype 对象和某个实例之间的关系.
alert(Cat.prototype.isPrototypeOf(cat1)); //true
alert(Cat.prototype.isPrototypeOf(cat2)); //true
2> hasOwnProperty()
每个实例对象都有一个 hasOwnProperty() 方法, 用来判断某一个属性到底是本地属性, 还是继承自 prototype 对象的属性.
alert(cat1.hasOwnProperty("name")); // true
alert(cat1.hasOwnProperty("type")); // false
3> in 运算符
in 运算符可以用来判断, 某个实例是否含有某个属性, 不管是不是本地属性.
alert("name" in cat1); // true
alert("type" in cat1); // true
in 运算符还可以用来遍历某个对象的所有属性.
for(var prop in cat1) {
alert("cat1["+prop+"]="+cat1[prop]);
}
来源: http://www.jianshu.com/p/f241fc146612