function Person(name, age) {
this.name = name || "person";
this.age = age || 0;
}
Person.prototype = {
LEG_NUM:2,
ARM_NUM:2,
sayHi: function () {
console.log("my name is" + this.name + "my age is " + this.age + "years old");
},
walking: function () {
console.log(this.name + "is walking");
}
}
function Student(name, age, classname) {
Person.call(this, name, age);
this.classname = classname;
}
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
Student.prototype = {
sayHi: function () {
console.log("my name is " + this.name + "my age is " + this.age + "my class is " + this.classname);
},
learn: function (obj) {
console.log(this.name + "is learning..." + obj);
}
}
var leo = new Student("leo", 12, "class 2,grade 3");
leo.walking();
leo.sayHi();
leo.learn("math");
console.log(leo.LEG_NUM);
console.log(leo.ARM_NUM);
去掉子类的原型方法就能用了????
刚看了书,楼上说的极是,不能使用对象字面量创建原型方法,这样会重写原型链。
Student.prototype = {
sayHi: function () {
console.log("my name is " + this.name + "my age is " + this.age + "my class is " + this.classname);
},
learn: function (obj) {
console.log(this.name + "is learning..." + obj);
}
}
这一句不能这么写,这样等于把Student.prototype的值更改为后面所定义的对象,而不是父类的实例,包括你上面定义的constructor属性的定义也会失效,应该写成:
Student.prototype.sayHi=function () {
console.log("my name is " + this.name + "my age is " + this.age + "my class is " + this.classname);
};
Student.prototype.learn=function (obj) {
console.log(this.name + "is learning..." + obj);
};
切记:不要用字面量写法,因为它会整个替换掉prototype所指向的对象