我对我们使用原型继承的原因有一些基本的了解,在我的应用程序中做一些事情时,我意识到一旦将同名函数添加到其原型中,就无法真正访问函数。为什么,这是我的代码:
function person(firstname, lastname) {
this.firstname = firstname,
this.lastname = lastname,
this.greet = function() {
console.log('hey there', this.lastname + ' ' + this.firstname);
}
}
var jane = new person('jane', 'Doe');
jane.greet();
var john = new person('john', 'smith');
john.greet();
function person(firstname, lastname) {
this.firstname = firstname,
this.lastname = lastname
}
person.prototype.greet = function() {
console.log('hey there', this.lastname + ' ' + this.firstname);
}
var jane = new person('jane', 'Doe');
jane.greet();
var john = new person('john', 'smith');
john.greet();
引发的错误是:
"test.js:10
jane.greet();
^
TypeError: jane.greet is not a function"