@@ -47,8 +47,8 @@ bolt.bark(); // "Woof!"
4747
4848需要注意的是:
4949
50- * ` .makeSound ` 未在 ` Dog ` 上定义,因此 JavaScript 引擎会向上查找原型链,并在继承的 ` Animal ` 上找到 ` .makeSound ` 。
51- * 不再推荐使用 ` Object.create() ` 来构建继承链。请改用 ` Object.setPrototypeOf() ` 。
50+ * ` .makeSound ` 未在 ` Dog ` 上定义,因此 JavaScript 引擎会向上查找原型链,并在继承的 ` Animal ` 上找到 ` .makeSound ` 。
51+ * 不再推荐使用 ` Object.create() ` 来构建继承链。请改用 ` Object.setPrototypeOf() ` 。
5252
5353***
5454
@@ -105,42 +105,42 @@ console.log(john.sayHello); // undefined
1051053 . ** 构造函数** :JavaScript 提供了构造函数来创建对象。当一个函数与 new 关键字一起用作构造函数时,新对象的原型 (` [[Prototype]] ` ) 将设置为构造函数 的原型属性。
106106
107107``` js live
108- // Define a constructor function
108+ // 定义一个构造函数
109109function Animal (name ) {
110110 this .name = name;
111111}
112112
113- // Add a method to the prototype
113+ // 将一个方法添加到原型上
114114Animal .prototype .sayName = function () {
115- console .log (` My name is ${ this .name } ` );
115+ console .log (` 我的名字是 ${ this .name } ` );
116116};
117117
118- // Define a new constructor function
118+ // 定义一个新的构造函数
119119function Dog (name , breed ) {
120120 Animal .call (this , name);
121121 this .breed = breed;
122122}
123123
124- // Set the prototype of Dog to be a new instance of Animal
125- Dog .prototype = Object . create ( Animal .prototype );
124+ // 设置 Dog 的原型以继承自 Animal 的原型
125+ Object . setPrototypeOf ( Dog .prototype , Animal .prototype );
126126
127- // Add a method to the Dog prototype
127+ // 将一个方法添加到 Dog 的原型上
128128Dog .prototype .bark = function () {
129- console .log (' Woof! ' );
129+ console .log (' 汪! ' );
130130};
131131
132- // Create a new object using the Dog constructor function
132+ // 使用 Dog 构造函数创建一个新对象
133133let fido = new Dog (' Fido' , ' Labrador' );
134134
135- // The new object has access to the methods defined on its own prototype and the Animal prototype
136- fido .bark (); // "Woof! "
137- fido .sayName (); // "My name is Fido"
135+ // 新对象可以访问在其自身原型和 Animal 原型上定义的方法
136+ fido .bark (); // "汪! "
137+ fido .sayName (); // "我的名字是 Fido"
138138
139- // If we try to access a method that doesn't exist on the Dog prototype or the Animal prototype, JavaScript will return undefined
139+ // 如果我们尝试访问 Dog 原型或 Animal 原型上不存在的方法, JavaScript 将返回 undefined
140140console .log (fido .fly ); // undefined
141141```
142142
143- 4 . ** ` Object.create() ` ** :此方法使用指定原型对象和属性创建一个新对象。这是设置原型继承的一种直接方法。如果您通过 ` Object.create(null) ` 创建一个对象,它将不会从 ` Object.prototype ` 继承任何属性。这意味着该对象将没有任何内置属性或方法,例如 ` toString() ` 、` hasOwnProperty() `
143+ 4 . ** ` Object.create() ` ** : 此方法创建一个新对象,其内部 ` [[Prototype]] ` 直接链接到指定的原型对象。这是创建从另一个特定对象继承的对象的最直接方法,无需涉及构造函数。如果通过 ` Object.create(null) ` 创建一个对象,它将不会从 ` Object.prototype ` 继承任何属性。这意味着该对象将没有任何内置属性或方法,如 ` toString() ` 、` hasOwnProperty() ` ,
144144
145145``` js live
146146// Define a prototype object
0 commit comments