【问题标题】:What type of inheritance is present in this example (apart from prototypal)这个例子中存在什么类型的继承(除了原型)
【发布时间】:2018-03-14 06:16:58
【问题描述】:

我在 javaScript 中做了以下示例。有一个构造函数,我正在创建一个实例。现在,此实例直接从构造函数 (printName) 获得 1 个方法,并通过构造函数的原型 (printAge) 获得一个方法。

我可以得出结论,printAge 可以通过 prototypal Inheritance 调用得到,但 printName 是否代表任何类型的继承(因为它自动获取到新创建的实例,是经典继承还是其他?)。

<html> 
<head></head>
<body>

<script>

var person = function(name, age){
this.name = name;
this.age = age; 
this.printName = function(){
    alert(this.name);
}
}
person.prototype.printAge = function(){
alert(this.age);
}

var person1 = new person("Jack", 29); 
person1.printName();
person1.printAge();

</script>

</body>
</html> 

由于创建了新实例,它从构造函数中获取 printName。它代表任何一种继承吗?

【问题讨论】:

    标签: javascript html inheritance prototypal-inheritance


    【解决方案1】:

    不,printName 与继承无关。当您通过person function-constructor 创建对象时,每个对象都会获得自己的printName prpoerty 副本,这是一个函数。当我为一个对象更改该属性时,对于其他对象,它不会被更改。

    var person = function(name, age){
       this.name = name;
       this.age = age; 
       this.printName = function() {
           alert(this.name);
       }
    };
    
    person.prototype.printAge = function() {
       alert(this.age);
    };
    
    var person1 = new person("Jack", 29); 
    var person2 = new person("Alex", 30); 
    person1.printName = function() { console.log('Changed !!!'); };
    
    person1.printName();
    person2.printName();

    所以它只是一个引用函数的属性。您拥有名称为 age 的类似属性,但 age 包含原始值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-04
      • 1970-01-01
      • 2016-10-31
      • 1970-01-01
      • 2010-10-27
      • 1970-01-01
      • 2023-03-31
      相关资源
      最近更新 更多