原型继承的新手-Can'找不到Undefined变量的问题

New to Prototypal Inheritance - Can't find the issue with Undefined variable

本文关键字:找不到 Undefined 变量 问题 继承 新手 -Can 原型      更新时间:2023-09-26

我对JavaScript中的原型继承很陌生,我正在努力了解这里的问题所在。

简单的代码,我们有两个对象pet和pet2,pet2继承自pet。

var Pet = function() {
    this.type="Dog";
    this.age = 4;
};
var Pet2 = function() {
    this.breed = "Kashon";
};
pet = new Pet();
pet2 = new Pet2();

if (Object.create !==  'function') {
    Object.create = function(oldObject) {
        function F() {}
        F.prototype = oldObject;
        return new F();
    };    
}
pet2 = Object.create(pet);

问题是,当我试图访问pet2.bread时,由于某种原因,它是未定义的,为什么会这样?

alert(pet2.type); //ok
alert(pet2.age);  //ok
alert(pet2.breed); //comes out undefined?

任何帮助都很好:D

当您使用Object.create时,您将旧对象指定为原型(例如,Pet)。当然,Pet2的任何属性都不会存在。您应该使用原型来"继承"对象,例如:Pet2.prototype = new Pet;

var Pet = function() {
  this.type="Dog";
  this.age = 4;
};
var Pet2 = function() {
  this.breed = "Kashon";
};
Pet2.prototype = new Pet; // Pet2 inherits Pet
pet = new Pet();
pet2 = new Pet2();
alert(pet2.type); //ok
alert(pet2.age);  //ok
alert(pet2.breed); // ok?

http://jsfiddle.net/U66aX/

这里有很多问题。

  • 你把伪古典与原型继承混合在一起。这并不是说不能做到,但我只会坚持其中一个。既然你在问原型,你应该远离new(除了在Object.create函数内部)
  • 您设置了两次pet2,因此覆盖了使其成为Pet2实例的初始赋值
  • 你从来没有说Pet2继承自Pet1

以下是原型示例的样子:http://jsfiddle.net/NsRMA/

var Pet1 = {
  type: "Dog",
  age: 4
};
// Make Pet2 inherit from Pet1
var Pet2 = Object.create(Pet1);
// Add new properties to Pet2, this can and should be done 
// by passing another argument to Object.create , but any 
// hacked version can't support it
Pet2.breed = "Kashon";
// Now create an object that inherits from Pet2 (and consequently, Pet1)
var pet = Object.create(Pet2);
alert(pet.type); //ok
alert(pet.age);  //ok
alert(pet.breed); //ok