JavaScript继承未按预期工作

JavaScript继承未按预期工作,javascript,inheritance,Javascript,Inheritance,我有我的主对象: var Person = function() { this.canTalk = true; } 方法我希望所有子对象都继承: Person.prototype.greet = function() { if( this.canTalk ) { console.log( 'Hi, I am ' + this.name ); } } 继承自Employee var Employee = function( name, title)

我有我的主对象:

var Person = function() {
    this.canTalk = true;
}
方法我希望所有子对象都继承:

Person.prototype.greet = function() {
    if( this.canTalk ) {
        console.log( 'Hi, I am ' + this.name );
    }
}
继承自
Employee

  var Employee = function( name, title) {
        Person.call( this );
        this.name = name;
        this.title = title;
    }
实例化:

var robert = new Employee( "Robert Rocha", "Software Developer" );
robert.greet();
greet()
获取错误:
uncaughttypeerror:robert.greet不是函数


我做错了什么?

您需要扩展
员工的原型

Employee.prototype = Object.create(Person.prototype);
Employee.prototype.constructor = Employee;

您需要做的关键事情是设置原型链。您正确地调用了父构造函数,并向其传递了this的值。您可以非常简单地执行此操作:

Employee.prototype = Person.prototype;
然而,现在当您向Person添加一个方法时,Employee也可以访问它。如果您有一个特殊的用例,这将起作用,但通常您不想这样做

使用更常见的方法,并且当您向Employee.prototype添加方法时,Person将无法使用该方法

Employee.prototype = Object.create(Person.prototype);

请注意,您仍然在过度编写Employee.prototype,并且需要在过度编写之后定义方法

我认为简单地给原型赋值会导致所有子对象继承。啊,好吧,我想我明白了。可以说,
Object.prototype
语句类似于说,“我想将blah扩展到当前对象”,而Object.create()`指定您要扩展的对象是什么?不是真的
Object.prototype
已经存在,因此我将使用
MyFunc.prototype
是我希望
MyFunc
的所有实例都具有这些属性
Object.create
只是复制而已。@RobertRocha仅供参考,要获得任何给定对象的实际原型,您需要
Object.getPrototypeOf(obj)
。员工原型不是从Person原型继承的。您正在调用Person构造函数,但没有从Person原型中获取任何数据。它“有效”,是的,但这是一种非常糟糕的做法-您在此处设置的原型链不只是供参考: