Closed Ge-yuan-jun closed 8 years ago
不使用构造继承时,在控制台输出的结果不符合您所写的文章的预期。不知道是不是我的代码有问题
function Parent(name, age) { this.name = name; this.age = age; } Parent.prototype.getName = function() { return this.name; } Parent.prototype.getAge = function() { return this.age; } Parent.prototype.love = function() { game: ['FPS']; } Parent.pay = function() { return 1000; } //不调用构造方法实现 function Son() {}; Son.prototype = new Parent(); Son.prototype.constructor = Son; var parent = new Parent('jack', 40); var son = new Son('tom', 20); console.log('sonName: ' + son.getName());//sonName: undefined console.log('parentName: ' + parent.getName());//parentName: jack console.log('---------------'); console.log(Son.prototype.constructor == Son);//true console.log(son instanceof Son);//true console.log(son instanceof Parent);//true console.log(son instanceof Object);//true Son.prototype.getName = function() { return this.name + " has a good son"; } console.log('---------------'); console.log('sonName: ' + son.getName());//sonName: undefiend has a ggod son console.log('parentName: ' + parent.getName());//parentName:jack
Son的构造方法没有参数,上面的是没有问题的,如果有参数,需要在Son的构造方法中调用父类的构造方法。 我已经增加说明: https://github.com/xuanxiao2013/f2e-practice/blob/master/javascript-inherit/inherit1.js
不使用构造继承时,在控制台输出的结果不符合您所写的文章的预期。不知道是不是我的代码有问题