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
请注意,我们仅传入了this
到call()
中 - 不需要其他参数,因为我们不会继承通过参数设置的父级的任何属性。
到目前为止一切看起来都还行,但是我们遇到问题了。我们已经定义了一个新的构造器,这个构造器默认有一个空的原型属性。我们需要让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?
Teacher.prototype = Object.create(Person.prototype);- 这里我们的老朋友
create()
又来帮忙了——在这个例子里我们用这个函数来创建一个和Person.prototype
一样的新的原型属性值(这个属性指向一个包括属性和方法的对象),然后将其作为Teacher.prototype
的属性值。这意味着Teacher.prototype
现在会继承Person.prototype
的所有属性和方法。Teacher()
的prototype
的constructor
属性指向的是Person()
, 这是由我们生成Teacher()
的方式决定的。(这篇 Stack Overflow post 文章会告诉您详细的原理) — 将您写的页面在浏览器中打开,进入JavaScript控制台,输入以下代码来确认:
- Teacher.prototype.constructor-
Teacher.prototype.constructor = Teacher;-
Teacher.prototype.constructor
就会得到Teacher()
。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
.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.Object.defineProperty(Teacher.prototype, 'constructor', { + value: Teacher, + enumerable: false, // so that it does not appear in 'for in' loop + writable: true });+
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的原型上定义它—把以下代码添加到您代码的底部:
注:如果你编写时遇到困难,代码无法运行,那么可以查看我们的完成版本(也可查看 可运行的在线示例)。
-总结一下,您应该基本了解了以下三种属性或者方法:
+总结一下,你需要在实践中考虑到下面四类属性或方法
this.x = x
类型的行;在内置的浏览器代码中,它们是可用于对象实例的成员(通常通过使用new
关键字调用构造函数来创建,例如var myInstance = new myConstructor()
)。Object.keys()
。myConstructor.prototype.x()
。this.x = x
类型的行;在浏览器内已经构建好的代码中,它们是可用于对象实例的成员(这些对象实例通常使用new
关键字调用构造函数来创建,例如var myInstance = new myConstructor()
)。Object.keys()
。它们一般被称作静态属性或静态方法。myConstructor.prototype.x()
。let teacher1 = new Teacher( 'Chris' );
and then teacher1.name
), or an object literal (let teacher1 = { name : 'Chris' }
and then teacher1.name
).如果您现在觉得一团浆糊,别担心——您现在还处于学习阶段,不断练习才会慢慢熟悉这些知识。
+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:
+ +constructor()
method defines the constructor function that represents our Person
class.greeting()
and farewell()
are class methods. Any methods you want associated with the class are defined inside it, after the constructor. In this example, we've used template literals rather than string concatenation to make the code easier to read.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.
+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 Teacher
and 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).
+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:
_subject
property of the snape
object we can use the snape.subject
getter method._subject
property we can use the snape.subject="new value"
setter method.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的强大和灵活性正是来自于它的对象体系和继承方式,这很值得花时间去好好理解下它是如何工作的。
-- cgit v1.2.3-54-g00ecf