【问题标题】:How to define properties subclasses in javascript如何在javascript中定义属性子类
【发布时间】:2012-07-05 23:28:32
【问题描述】:

我是 Javascript 新手,在寻找合适的解决方案时遇到了一些麻烦。在定义具有属性的新子类时,这样做的正确/最佳实践是什么?我从 MDN 中提取了下面的代码,但它没有讨论如何通过继承传递属性。我需要的是一个超类和子类,它们具有在实例化期间定义的属性。超类的属性需要对所有子类可用,而子类的属性将只属于子类。有人可以指出我正确的方向吗?

// define the Person Class  
function Person() {}  

Person.prototype.walk = function(){  
  alert ('I am walking!');  
};  
Person.prototype.sayHello = function(){  
  alert ('hello');  
};  

// define the Student class  
function Student() {  
  // Call the parent constructor  
  Person.call(this);  
}  

// inherit Person  
Student.prototype = new Person();  

// correct the constructor pointer because it points to Person  
Student.prototype.constructor = Student;  

// replace the sayHello method  
Student.prototype.sayHello = function(){  
  alert('hi, I am a student');  
}  

// add sayGoodBye method  
Student.prototype.sayGoodBye = function(){  
   alert('goodBye');
}  

var student1 = new Student();  
student1.sayHello();  
student1.walk();  
student1.sayGoodBye();  

// check inheritance  
alert(student1 instanceof Person); // true   
alert(student1 instanceof Student); // true

【问题讨论】:

    标签: javascript oop class inheritance object


    【解决方案1】:

    可以使用this 关键字访问实例变量。您可以并且应该在构造函数中初始化实例变量:

    function Person(name) {
        this.name = name;
    }
    
    var bob = new Person("Bob");
    alert(bob.name);
    

    jsFiddle

    当你子类化时,超类的实例变量将自动可供子类使用。

    【讨论】:

    • 知道了,但是如何将实例变量传递给子类。上面的代码展示了以下关于继承的内容... // 定义 Student 类 function Student() { // 调用父构造函数 Person.call(this);我将如何将变量传递给子类并同时传递超类变量?
    猜你喜欢
    • 2014-11-05
    • 1970-01-01
    • 2021-10-21
    • 2018-08-13
    • 2020-09-06
    • 2022-11-12
    • 2015-09-01
    • 2019-05-20
    • 2022-11-14
    相关资源
    最近更新 更多