首页 > > > 关于javascript原型的一个小问题
如题,创建一个People构造函数
function People(name,weight){
this.name = name;
this.weight = weight;
this.speak = function(){
return 'I am '+this.name+",and my weight is "+this.weight;
}
}
/*
*/
People.prototype.height = 203;
People.prototype.run = function(){
return "I am running";
}
//或者这么写(第二种)
/*
People.prototype = {
weight:70,
height:175,
run:function(){
return "I am running";
}
};
*/
var james = new People("James",113);
console.log(james.run());//I am running
console.log(james.constructor.prototype.constructor);//People()
console.log(james.constructor.prototype.height);//203
//console.log(james.constructor.prototype.height);//undefined当用第二种方式给原型添加属性时,实例化james对象后,没法访问构造器函数上的原型属性,为undefined。但是用第一种方式书写,就可以访问,得到203。
请问各位,这是一个什么原因呀,是写法不对嘛,写法不对的话,用第二种方式写的时候,还是可以访问其run方法的呀,还是其它什么问题?求指教,谢谢!
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2249/viewspace-3168906/ ,如需转载,请注明出处,否则将追究法律责任。