From c1a9587bf17769abf1b3fd51da016842f0998fef Mon Sep 17 00:00:00 2001 From: PocketZ <45301505+pocketdr@users.noreply.github.com> Date: Sun, 30 May 2021 14:37:49 +0800 Subject: Update Learn/JavaScript/Objects/Inheritance, zh-CN (#1032) --- .../javascript/objects/inheritance/index.html | 233 ++++++++++++++++++--- 1 file changed, 208 insertions(+), 25 deletions(-) (limited to 'files/zh-cn/learn/javascript/objects/inheritance/index.html') diff --git a/files/zh-cn/learn/javascript/objects/inheritance/index.html b/files/zh-cn/learn/javascript/objects/inheritance/index.html index c7b564d978..eca486d343 100644 --- a/files/zh-cn/learn/javascript/objects/inheritance/index.html +++ b/files/zh-cn/learn/javascript/objects/inheritance/index.html @@ -127,31 +127,24 @@ translation_of: Learn/JavaScript/Objects/Inheritance

请注意,我们仅传入了thiscall()中 - 不需要其他参数,因为我们不会继承通过参数设置的父级的任何属性。

-

设置 Teacher() 的原型和构造器引用

+

设置 Teacher() 的原型和构造器引用

-

到目前为止一切看起来都还行,但是我们遇到问题了。我们已经定义了一个新的构造器,这个构造器默认有一个空的原型属性。我们需要让Teacher()Person()的原型对象里继承方法。我们要怎么做呢?

+

All is good so far, but we have a problem. We have defined a new constructor, and it has a prototype property, which by default just contains an object with a reference to the constructor function itself. It does not contain the methods of the Person constructor's prototype property. To see this, enter Object.getOwnPropertyNames(Teacher.prototype) into either the text input field or your JavaScript console. Then enter it again, replacing Teacher with Person. Nor does the new constructor inherit those methods. To see this, compare the outputs of Person.prototype.greeting and Teacher.prototype.greeting. We need to get Teacher() to inherit the methods defined on Person()'s prototype. So how do we do that?

    -
  1. 在您先前添加的代码的下面增加以下这一行: -
    Teacher.prototype = Object.create(Person.prototype);
    - 这里我们的老朋友create()又来帮忙了——在这个例子里我们用这个函数来创建一个和Person.prototype一样的新的原型属性值(这个属性指向一个包括属性和方法的对象),然后将其作为Teacher.prototype的属性值。这意味着Teacher.prototype现在会继承Person.prototype的所有属性和方法。
  2. -
  3. 接下来,在我们动工之前,还需要完成一件事 — 现在Teacher()prototypeconstructor属性指向的是Person(), 这是由我们生成Teacher()的方式决定的。(这篇 Stack Overflow post 文章会告诉您详细的原理) — 将您写的页面在浏览器中打开,进入JavaScript控制台,输入以下代码来确认: -
    Teacher.prototype.constructor
    -
  4. -
  5. 这或许会成为很大的问题,所以我们需要将其正确设置——您可以回到源代码,在底下加上这一行代码来解决: -
    Teacher.prototype.constructor = Teacher;
    -
  6. -
  7. 当您保存并刷新页面以后,输入Teacher.prototype.constructor就会得到Teacher()
  8. +
  9. Add the following line below your previous addition: +
    Teacher.prototype = Object.create(Person.prototype);
    + Here our friend create() comes to the rescue again. In this case we are using it to create a new object and make it the value of Teacher.prototype. The new object has Person.prototype as its prototype and will therefore inherit, if and when needed, all the methods available on Person.prototype.
  10. +
  11. We need to do one more thing before we move on. After adding the last line, Teacher.prototype's constructor property is now equal to Person(), because we just set Teacher.prototype to reference an object that inherits its properties from Person.prototype! Try saving your code, loading the page in a browser, and entering Teacher.prototype.constructor into the console to verify.
  12. +
  13. This can become a problem, so we need to set this right. You can do so by going back to your source code and adding the following line at the bottom: +
    Object.defineProperty(Teacher.prototype, 'constructor', {
    +    value: Teacher,
    +    enumerable: false, // so that it does not appear in 'for in' loop
    +    writable: true });
    +
  14. +
  15. Now if you save and refresh, entering Teacher.prototype.constructor should return Teacher(), as desired, plus we are now inheriting from Person()!
-
-

注:每一个函数对象(Function)都有一个prototype属性,并且只有函数对象有prototype属性,因为prototype本身就是定义在Function对象下的属性。当我们输入类似var person1=new Person(...)来构造对象时,JavaScript实际上参考的是Person.prototype指向的对象来生成person1。另一方面,Person()函数是Person.prototype的构造函数,也就是说Person===Person.prototype.constructor(不信的话可以试试)。

- -

在定义新的构造函数Teacher时,我们通过function.call来调用父类的构造函数,但是这样无法自动指定Teacher.prototype的值,这样Teacher.prototype就只能包含在构造函数里构造的属性,而没有方法。因此我们利用Object.create()方法将Person.prototype作为Teacher.prototype的原型对象,并改变其构造器指向,使之与Teacher关联。

- -

任何您想要被继承的方法都应该定义在构造函数的prototype对象里,并且永远使用父类的prototype来创造子类的prototype,这样才不会打乱类继承结构。

-
-

向 Teacher() 添加一个新的greeting()函数

为了完善代码,您还需在构造函数Teacher()上定义一个新的函数greeting()。最简单的方法是在Teacher的原型上定义它—把以下代码添加到您代码的底部:

@@ -206,18 +199,208 @@ teacher1.greeting();

注:如果你编写时遇到困难,代码无法运行,那么可以查看我们的完成版本(也可查看 可运行的在线示例)。

-

对象成员总结

+

对象成员总结

-

总结一下,您应该基本了解了以下三种属性或者方法:

+

总结一下,你需要在实践中考虑到下面四类属性或方法

    -
  1. 那些定义在构造器函数中的、用于给予对象实例的。这些都很容易发现 - 在您自己的代码中,它们是构造函数中使用this.x = x类型的行;在内置的浏览器代码中,它们是可用于对象实例的成员(通常通过使用new关键字调用构造函数来创建,例如var myInstance = new myConstructor())。
  2. -
  3. 那些直接在构造函数上定义、仅在构造函数上可用的。这些通常仅在内置的浏览器对象中可用,并通过被直接链接到构造函数而不是实例来识别。 例如Object.keys()
  4. -
  5. 那些在构造函数原型上定义、由所有实例和对象类继承的。这些包括在构造函数的原型属性上定义的任何成员,如myConstructor.prototype.x()
  6. +
  7. 那些定义在构造器函数中,用于给予对象实例的属性或方法。它们都很容易发现——在您自己的代码中,它们是构造函数中使用this.x = x类型的行;在浏览器内已经构建好的代码中,它们是可用于对象实例的成员(这些对象实例通常使用new关键字调用构造函数来创建,例如var myInstance = new myConstructor())。
  8. +
  9. 那些直接在构造函数上定义,仅在构造函数上可用的属性或方法。它们通常仅在浏览器的内置对象中可用,并通过被直接链接到构造函数来识别,而不是实例。例如Object.keys()它们一般被称作静态属性或静态方法
  10. +
  11. 那些在构造函数原型上定义,由所有实例和对象类继承的属性或方法。它们包括在构造函数的原型属性上定义的任何成员,如myConstructor.prototype.x()
  12. +
  13. Those available on an object instance, which can either be an object created when a constructor is instantiated like we saw above (so for example let teacher1 = new Teacher( 'Chris' ); and then teacher1.name), or an object literal (let teacher1 = { name : 'Chris' } and then teacher1.name).

如果您现在觉得一团浆糊,别担心——您现在还处于学习阶段,不断练习才会慢慢熟悉这些知识。

+

ECMAScript 2015 Classes

+ +

ECMAScript 2015 introduces class syntax to JavaScript as a way to write reusable classes using easier, cleaner syntax, which is more similar to classes in C++ or Java. In this section we'll convert the Person and Teacher examples from prototypal inheritance to classes, to show you how it's done.

+ +
+

Note: This modern way of writing classes is supported in all modern browsers, but it is still worth knowing about the underlying prototypal inheritance in case you work on a project that requires supporting a browser that doesn't support this syntax (most notably Internet Explorer).

+
+ +

Let's look at a rewritten version of the Person example, class-style:

+ +
class Person {
+  constructor(first, last, age, gender, interests) {
+    this.name = {
+      first,
+      last
+    };
+    this.age = age;
+    this.gender = gender;
+    this.interests = interests;
+  }
+
+  greeting() {
+    console.log(`Hi! I'm ${this.name.first}`);
+  };
+
+  farewell() {
+    console.log(`${this.name.first} has left the building. Bye for now!`);
+  };
+}
+
+ +

The class statement indicates that we are creating a new class. Inside this block, we define all the features of the class:

+ + + +

We can now instantiate object instances using the new operator, in just the same way as we did before:

+ +
let han = new Person('Han', 'Solo', 25, 'male', ['Smuggling']);
+han.greeting();
+// Hi! I'm Han
+
+let leia = new Person('Leia', 'Organa', 19, 'female', ['Government']);
+leia.farewell();
+// Leia has left the building. Bye for now
+
+ +
+

Note: Under the hood, your classes are being converted into Prototypal Inheritance models — this is just syntactic sugar. But I'm sure you'll agree that it's easier to write.

+
+ +

Inheritance with class syntax

+ +

Above we created a class to represent a person. They have a series of attributes that are common to all people; in this section we'll create our specialized Teacher class, making it inherit from Person using modern class syntax. This is called creating a subclass or subclassing.

+ +

To create a subclass we use the extends keyword to tell JavaScript the class we want to base our class on,

+ +
class Teacher extends Person {
+  constructor(subject, grade) {
+    this.subject = subject;
+    this.grade = grade;
+  }
+}
+ +

but there's a little catch.

+ +

Unlike old-school constructor functions where the new operator does the initialization of this to a newly-allocated object, this isn't automatically initialized for a class defined by the extends keyword, i.e the sub-classes.

+ +

Therefore running the above code will give an error:

+ +
Uncaught ReferenceError: Must call super constructor in derived class before
+accessing 'this' or returning from derived constructor
+ +

For sub-classes, the this initialization to a newly allocated object is always dependant on the parent class constructor, i.e the constructor function of the class from which you're extending.

+ +

Here we are extending the Person class — the Teacher sub-class is an extension of the Person class. So for Teacher, the this initialization is done by the Person constructor.

+ +

To call the parent constructor we have to use the super() operator, like so:

+ +
class Teacher extends Person {
+  constructor(subject, grade) {
+    super(); // Now 'this' is initialized by calling the parent constructor.
+    this.subject = subject;
+    this.grade = grade;
+  }
+}
+ +

There is no point having a sub-class if it doesn't inherit properties from the parent class.
+It is good then, that the super() operator also accepts arguments for the parent constructor.

+ +

Looking back to our Person constructor, we can see it has the following block of code in its constructor method:

+ +
 constructor(first, last, age, gender, interests) {
+   this.name = {
+     first,
+     last
+   };
+   this.age = age;
+   this.gender = gender;
+   this.interests = interests;
+} 
+ +

Since the super() operator is actually the parent class constructor, passing it the necessary arguments of the Parent class constructor will also initialize the parent class properties in our sub-class, thereby inheriting it:

+ +
class Teacher extends Person {
+  constructor(first, last, age, gender, interests, subject, grade) {
+    super(first, last, age, gender, interests);
+
+    // subject and grade are specific to Teacher
+    this.subject = subject;
+    this.grade = grade;
+  }
+}
+
+ +

Now when we instantiate Teacher object instances, we can call methods and properties defined on both Teacherand Person as we'd expect:

+ +
let snape = new Teacher('Severus', 'Snape', 58, 'male', ['Potions'], 'Dark arts', 5);
+snape.greeting(); // Hi! I'm Severus.
+snape.farewell(); // Severus has left the building. Bye for now.
+snape.age // 58
+snape.subject; // Dark arts
+
+ +

Like we did with Teachers, we could create other subclasses of Person to make them more specialized without modifying the base class.

+ +
+

Note: You can find this example on GitHub as es2015-class-inheritance.html (see it live also).

+
+ +

Getters and Setters

+ +

There may be times when we want to change the values of an attribute in the classes we create or we don't know what the final value of an attribute will be. Using the Teacher example, we may not know what subject the teacher will teach before we create them, or their subject may change between terms.

+ +

We can handle such situations with getters and setters.

+ +

Let's enhance the Teacher class with getters and setters. The class starts the same as it was the last time we looked at it.

+ +

Getters and setters work in pairs. A getter returns the current value of the variable and its corresponding setter changes the value of the variable to the one it defines.

+ +

The modified Teacher class looks like this:

+ +
class Teacher extends Person {
+  constructor(first, last, age, gender, interests, subject, grade) {
+    super(first, last, age, gender, interests);
+    // subject and grade are specific to Teacher
+    this._subject = subject;
+    this.grade = grade;
+  }
+
+  get subject() {
+    return this._subject;
+  }
+
+  set subject(newSubject) {
+    this._subject = newSubject;
+  }
+}
+
+ +

In our class above we have a getter and setter for the subject property. We use _ to create a separate value in which to store our name property. Without using this convention, we would get errors every time we called get or set. At this point:

+ + + +

The example below shows the two features in action:

+ +
// Check the default value
+console.log(snape.subject) // Returns "Dark arts"
+
+// Change the value
+snape.subject = "Balloon animals" // Sets _subject to "Balloon animals"
+
+// Check it again and see if it matches the new value
+console.log(snape.subject) // Returns "Balloon animals"
+
+ +
+

Note: You can find this example on GitHub as es2015-getters-setters.html (see it live also).

+
+ +
+

Note: Getters and setters can be very useful at times, for example when you want to run some code every time a property is requested or set. For simple cases, however, plain property access without a getter or setter will do just fine.

+
+

何时在 JavaScript 中使用继承?

特别是在读完这段文章内容之后,您也许会想 "天啊,这实在是太复杂了". 是的,您是对的,原型和继承代表了JavaScript这门语言里最复杂的一些方面,但是JavaScript的强大和灵活性正是来自于它的对象体系和继承方式,这很值得花时间去好好理解下它是如何工作的。

-- cgit v1.2.3-54-g00ecf