js:深入prototype(下:原型重写)
//当属性和方法特别多时,编写起来不是非常方便,能够通过json的格式来编写
//因为原型重写。并且没有通过Person.prototype来指定,此时的constructor不会再指向Person而是指向Object
//假设constructor真的比較重要,能够在json中说明原型的指向
function Person(){
}
Person.prototype = {
//constructor:Person, //手动指定constructor
name:"octopus",
age:23,
say:function(){
alert(this.name+":"+this.age);
}
}
var p1 = new Person();
p1.say(); //octopus:23
alert(p1.constructor==Person); //false
Person.prototype.sayHi(){
alert(this.name+":hi");
}
p1.sayHi(); //octopus:hi
//可是假设把原型重写放到new Person()之后。p1.sayHi(); //undefined:hi
function Person(){
}
var p1 = new Person();
Person.prototype.sayHi(){
alert(this.name+":hi");
}
p1.sayHi(); //undefined:hi
Person.prototype = {
//constructor:Person, //手动指定constructor
name:"octopus",
age:23,
say:function(){
alert(this.name+":"+this.age);
}
}
p1.sayHi(); //undefined:hi 有sayHi(),但没有name
var p2 = new Person();
p2.sayHi(); //报错:sayHi is not a function 这是由于 p2没有sayHi
原创文章如转载,请注明出处。本文首发于csdn站点:http://blog.csdn.net/magneto7/article/details/24922481