js原型实现
理解原型的基本概念
在JavaScript中,每个对象都有一个原型(prototype),原型本身也是一个对象。对象从原型继承属性和方法。原型链是JavaScript实现继承的机制。
使用构造函数创建对象
构造函数用于创建对象实例。通过new关键字调用构造函数时,会创建一个新对象,并将该对象的原型指向构造函数的prototype属性。
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
console.log(`Hello, my name is ${this.name}`);
};
const person1 = new Person('Alice');
person1.greet(); // 输出: Hello, my name is Alice
原型链继承
通过原型链,子构造函数可以继承父构造函数的属性和方法。子构造函数的prototype指向父构造函数的实例。
function Student(name, grade) {
Person.call(this, name);
this.grade = grade;
}
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
Student.prototype.study = function() {
console.log(`${this.name} is studying in grade ${this.grade}`);
};
const student1 = new Student('Bob', 5);
student1.greet(); // 输出: Hello, my name is Bob
student1.study(); // 输出: Bob is studying in grade 5
使用Object.create创建对象
Object.create方法可以创建一个新对象,并指定其原型。
const animal = {
speak() {
console.log(`${this.name} makes a noise.`);
}
};
const dog = Object.create(animal);
dog.name = 'Rex';
dog.speak(); // 输出: Rex makes a noise.
修改原型
原型可以在运行时动态修改,所有实例都会受到影响。
function Car(model) {
this.model = model;
}
const car1 = new Car('Tesla');
Car.prototype.drive = function() {
console.log(`${this.model} is driving.`);
};
car1.drive(); // 输出: Tesla is driving.
检查原型关系
使用instanceof和Object.getPrototypeOf可以检查对象的原型关系。
console.log(student1 instanceof Student); // true
console.log(student1 instanceof Person); // true
console.log(Object.getPrototypeOf(student1) === Student.prototype); // true
避免直接修改__proto__
虽然__proto__属性可以访问对象的原型,但直接修改它不推荐使用。应使用Object.create或Object.setPrototypeOf。
const cat = {
purr() {
console.log('Purring...');
}
};
const kitten = Object.create(cat);
kitten.purr(); // 输出: Purring...
使用ES6的class语法
ES6的class语法是原型的语法糖,简化了原型继承的写法。
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
speak() {
console.log(`${this.name} barks.`);
}
}
const d = new Dog('Rex');
d.speak(); // 输出: Rex barks.






