@@ -47,8 +47,8 @@ bolt.bark(); // "Woof!"
47
47
48
48
需要注意的是:
49
49
50
- * ` .makeSound ` 未在 ` Dog ` 上定义,因此 JavaScript 引擎会向上查找原型链,并在继承的 ` Animal ` 上找到 ` .makeSound ` 。
51
- * 不再推荐使用 ` Object.create() ` 来构建继承链。请改用 ` Object.setPrototypeOf() ` 。
50
+ * ` .makeSound ` 未在 ` Dog ` 上定义,因此 JavaScript 引擎会向上查找原型链,并在继承的 ` Animal ` 上找到 ` .makeSound ` 。
51
+ * 不再推荐使用 ` Object.create() ` 来构建继承链。请改用 ` Object.setPrototypeOf() ` 。
52
52
53
53
***
54
54
@@ -105,42 +105,42 @@ console.log(john.sayHello); // undefined
105
105
3 . ** 构造函数** :JavaScript 提供了构造函数来创建对象。当一个函数与 new 关键字一起用作构造函数时,新对象的原型 (` [[Prototype]] ` ) 将设置为构造函数 的原型属性。
106
106
107
107
``` js live
108
- // Define a constructor function
108
+ // 定义一个构造函数
109
109
function Animal (name ) {
110
110
this .name = name;
111
111
}
112
112
113
- // Add a method to the prototype
113
+ // 将一个方法添加到原型上
114
114
Animal .prototype .sayName = function () {
115
- console .log (` My name is ${ this .name } ` );
115
+ console .log (` 我的名字是 ${ this .name } ` );
116
116
};
117
117
118
- // Define a new constructor function
118
+ // 定义一个新的构造函数
119
119
function Dog (name , breed ) {
120
120
Animal .call (this , name);
121
121
this .breed = breed;
122
122
}
123
123
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 );
126
126
127
- // Add a method to the Dog prototype
127
+ // 将一个方法添加到 Dog 的原型上
128
128
Dog .prototype .bark = function () {
129
- console .log (' Woof! ' );
129
+ console .log (' 汪! ' );
130
130
};
131
131
132
- // Create a new object using the Dog constructor function
132
+ // 使用 Dog 构造函数创建一个新对象
133
133
let fido = new Dog (' Fido' , ' Labrador' );
134
134
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"
138
138
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
140
140
console .log (fido .fly ); // undefined
141
141
```
142
142
143
- 4 . ** ` Object.create() ` ** :此方法使用指定原型对象和属性创建一个新对象。这是设置原型继承的一种直接方法。如果您通过 ` Object.create(null) ` 创建一个对象,它将不会从 ` Object.prototype ` 继承任何属性。这意味着该对象将没有任何内置属性或方法,例如 ` toString() ` 、` hasOwnProperty() `
143
+ 4 . ** ` Object.create() ` ** : 此方法创建一个新对象,其内部 ` [[Prototype]] ` 直接链接到指定的原型对象。这是创建从另一个特定对象继承的对象的最直接方法,无需涉及构造函数。如果通过 ` Object.create(null) ` 创建一个对象,它将不会从 ` Object.prototype ` 继承任何属性。这意味着该对象将没有任何内置属性或方法,如 ` toString() ` 、` hasOwnProperty() ` ,
144
144
145
145
``` js live
146
146
// Define a prototype object
0 commit comments