Javascript继承问题

Javascript继承问题,javascript,inheritance,prototypal-inheritance,Javascript,Inheritance,Prototypal Inheritance,为什么下面代码中的版本2不会产生与版本1相同的结果 function person(name) { this.name = name; } function student(id, name) { this.id = id; // Version 1 //this.inherit_from_person = person; //this.inherit_from_person(name); // Version 2 person(name)

为什么下面代码中的版本2不会产生与版本1相同的结果

function person(name) {
    this.name = name;
}
function student(id, name) {
    this.id = id;
    // Version 1
    //this.inherit_from_person = person;
    //this.inherit_from_person(name);
    // Version 2
    person(name);
}
s = new student(5, 'Misha');
document.write(s.name); // Version 1    =>    Misha
                        // Version 2    =>    undefined

当您调用
person(name)
时,会调用
这个绑定到全局对象的
,因此这只是设置
窗口。name=“Misha”
。您需要
person.call(this,name)
将其显式绑定到右侧
this

在我看来,您正在尝试实现原型继承。下面是一个经典的例子,虽然使用不多。javascript中不需要复杂的继承,通常只需要一个实例。如果需要多个实例,模块模式可以与用于共享方法和属性的闭包一起使用,还可以提供私有和私有成员

// Person is the "base class"
function Person(name) {
  this.setName(name);
}

// Use setters and getters so properties are
// added appropriately.
Person.prototype.setName = function(name) {
  this.name = name;
}

// Add Person methods
Person.prototype.getName = function() {
  return this.name;
}

// Student inherits from Person and also has
// its own methods
function Student(name, id) {
  this.setId(id);
  this.setName(name);
}

// To inherit from Person, Student.prototype should
// be an instance of Person
Student.prototype = new Person();

// Add Student methods
Student.prototype.setId = function(id) {
  this.id = id;
}
Student.prototype.getId = function() {
  return this.id;
}

var p0 = new Student('Sally', '1234');
var p1 = new Person('James');

alert('p0\'s id is ' + p0.id + ' and name is: ' + p0.name);
alert('p1\'s name is: ' + p1.name);
alert('Is p0 a student? ' + (p0 instanceof Student));
alert('Is p1 a student? ' + (p1 instanceof Student));

请注意,instanceof操作符不是很可靠,但在上述情况下它可以正常工作。此外,所有方法和属性都是公共的,因此很容易重写。

非常感谢您提供的示例!