gpt4 book ai didi

javascript - 通过原型(prototype)继承,父对象的值没有改变

转载 作者:行者123 更新时间:2023-11-28 17:46:34 24 4
gpt4 key购买 nike

我是 javascript OOP 新手,请耐心等待

从继承对象 Student 更改父对象的值应该会更改该人的年龄,但我得到的值完全相同。

<script>
function Person(age){
this.age=age;
}

function Student(){}

var person=Student.prototype=new Person(10);
var oldAge=person.age;
Student.age=20;
var newAge=person.age;

alert("Person old age="+oldAge+"\New age="+newAge);
</script>

作为 personStudent 继承自同一个 Person 对象,那么学生和人员的年龄值都应该在更改 Student 的值时发生变化

我已经浏览过Prototypical inheritance - writing upJavaScript Inherited Properties Default Value问题

problem is i want to change the value of Person through Student which inherits the property of Person.

我认为这里遗漏了一些东西,请帮助我理解这一点。

最佳答案

JavaScript 中有两种用于实现继承的模式

  1. 原型(prototype)面向对象模式
  2. 构造函数面向对象模式

现在我将使用第一种方法

一些先决知识:

  1. 所有 JS 对象都有一个指向原型(prototype)的属性对象,因此除了它自己的属性之外,对象还可以访问自己原型(prototype)的属性

  2. __proto__ :所有对象都有的属性,this指向 该对象的原型(prototype)。

  3. Object.create(arg) :用于创建对象并初始化 他们的原型(prototype)或设置他们的 __proto__ 属性。

    Object.create MDN link

    下面的代码片段实现了继承,并允许您通过 Student 修改 Person 的值。:

function Person(age){ 
this.age=age;
this.getAge = function () { return this.age;}
};

function Student(){};

//Creating Person instance
var person = new Person(23);

console.log("Old Person age is " + person.age);

//Creating a student instance and inheriting it from person instance
//Object.create method creates a object whose __proto__ point to the object passed
//Thus student will be an object having a property __proto__ that would point to person instance
//This assosciation allows the instance of student to access insatnce of Person
var student = Object.create(person);

//Change age of person through student
student.__proto__.age = 24;

console.log("New Person age is " + person.age);

console.log("We can also call parent object methods from child" + " for e.g calling getAge from student" + student.getAge());

现在要使用第二种方法实现类似的效果,可以使用以下代码片段:

function Person(age){ 
this.age=age;
}

function Student(){}

//Create person instance
var person = new Person(23);

console.log("Old age of person is " + person.age);

//Inherit the person instance
Student.prototype = person;

//create a student object
var student = new Student();

//Change the person instance age value
//this change is possible because we
//can access person object through
//student.__proto__.
student.__proto__.age = 24;

console.log("New age of person is " + person.age);

关于javascript - 通过原型(prototype)继承,父对象的值没有改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46593620/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com