js高级原型与原型链练习题
时间: 2023-07-28 09:22:00 浏览: 53
好的,我可以为您提供一些 JS 高级原型与原型链的练习题,希望对您有所帮助。
1. 创建一个构造函数 Person,它有属性 name 和 age。创建一个对象 john,它的 name 是 "John",age 是 30。使用 Person 的原型对象添加一个方法 sayHello,它会在控制台输出 "Hello, my name is {name}!"。
```javascript
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.sayHello = function() {
console.log(`Hello, my name is ${this.name}!`);
};
const john = new Person("John", 30);
john.sayHello();
```
2. 创建一个构造函数 Animal,它有属性 name 和 type。创建一个对象 cat,它的 name 是 "Whiskers",type 是 "Cat"。使用 Object.create() 方法创建一个对象 dog,它的 name 是 "Fido",type 是 "Dog"。使用 Animal 的原型对象添加一个方法 sayType,它会在控制台输出 "{name} is a {type}."。
```javascript
function Animal(name, type) {
this.name = name;
this.type = type;
}
Animal.prototype.sayType = function() {
console.log(`${this.name} is a ${this.type}.`);
};
const cat = new Animal("Whiskers", "Cat");
const dog = Object.create(Animal.prototype, {
name: {
value: "Fido",
writable: true,
enumerable: true,
configurable: true
},
type: {
value: "Dog",
writable: true,
enumerable: true,
configurable: true
}
});
cat.sayType(); // Whiskers is a Cat.
dog.sayType(); // Fido is a Dog.
```
3. 创建一个构造函数 Shape,它有属性 color 和 name。创建一个对象 circle,它的 color 是 "red",name 是 "Circle"。创建一个对象 square,它的 color 是 "green",name 是 "Square"。使用 Shape 的原型对象添加一个方法 describe,它会在控制台输出 "This is a {color} {name}."。
```javascript
function Shape(color, name) {
this.color = color;
this.name = name;
}
Shape.prototype.describe = function() {
console.log(`This is a ${this.color} ${this.name}.`);
};
const circle = new Shape("red", "Circle");
const square = new Shape("green", "Square");
circle.describe(); // This is a red Circle.
square.describe(); // This is a green Square.
```
希望这些练习题能够帮助您巩固 JS 高级原型与原型链的知识。如果您有任何问题或需要进一步的帮助,请随时提问。