4

以下のコードのバージョン 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

ライブデモはこちら。

4

2 に答える 2

6

呼び出すと、グローバルオブジェクトにバインドされてperson(name)呼び出されるため、設定するだけです。明示的に右にバインドしたい。thiswindow.name = "Misha"person.call(this, name)this

于 2011-05-03T02:54:58.050 に答える
3

プロトタイプの継承を実装しようとしているように見えます。以下は典型的な例ですが、あまり使用されていません。複雑な継承は 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演算子はあまり信頼できないことに注意してください。ただし、上記の場合は正常に機能します。また、すべてのメソッドとプロパティは公開されているため、簡単に上書きできます。

于 2011-05-03T03:48:10.143 に答える