为什么在我们为其原型添加相同的函数时,无法访问作为对象属性的函数?

时间:2018-05-10 23:04:15

标签: javascript prototype

我对我们使用原型继承的原因有一些基本的了解,在我的应用程序中做一些事情时,我意识到一旦将同名函数添加到其原型中,就无法真正访问函数。为什么,这是我的代码:

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"

0 个答案:

没有答案