致良知
2015-06-04 11:25
function Person(name, age) { this.name = name; this.age = age; } Person.prototype.hi = function () { console.log('Hi,my name is ' + this.name + ",I'm " + this.age + 'years old now'); } Person.prototype.LEGS_NUM = 2; Person.prototype.ARMS_NUM = 2; Person.prototype.walk = function () { console.log(this.name + "is walking..."); } function Student(name, age, className) { Person.call(this, name, age); this.className = className; } Student.prototype.hi = function () { console.log("Hi,my name is " + this.name + "I'm" + this.age + "years old now,and from" + this.className + "."); } Student.prototype.learn = function (subject) { console.log(this.name + " is learning" + subject + 'at' + this.className + '.'); } Student.prototype=Object.create(Person.prototype); Student.prototype.constructor=Student; var bosn = new Student('Bosn', 28, 'Class 3,Grade 2' ) ; bosn.hi(); bosn.LEGS_NUM; bosn.walk(); bosn.learn('math');
很經典的錯誤咯,你先給Student.prototype對象增加了hi/learn方法,又通過Object.create(Person.prototype)把新的對象賦值給Student.prototype,原來你添加的hi/learn當然就沒有咯!!!
正確的辦法:先賦值Object.create(Person.prototype)之後,再對Student.prototype添加hi/learn等方法才行哦
嗯嗯,要先继承了才能重载(覆盖)
console.log(this.name + " is learning" + subject + 'at' + this.className + '.');
把单引号都改为双引号。
这个错:Uncaught TypeError: bosn.learn is not a function
JavaScript深入浅出
281112 学习 · 1020 问题
相似问题
回答 1
回答 2