【JavaScript】深入浅出JavaScript继承机制:解密原型、原型链与面向对象实战攻略
warning:
这篇文章距离上次修改已过193天,其中的内容可能已经有所变动。
// 定义一个父类
function Parent(name) {
this.name = name;
}
// 父类的方法
Parent.prototype.sayName = function() {
console.log('My name is ' + this.name);
};
// 子类构造函数
function Child(name, age) {
Parent.call(this, name); // 调用父类构造函数给子类实例设置name属性
this.age = age;
}
// 创建一个Parent的实例,将其作为Child的原型
Child.prototype = Object.create(Parent.prototype);
// 修正Child.prototype的构造器指向
Child.prototype.constructor = Child;
// 子类特有方法
Child.prototype.sayAge = function() {
console.log('I am ' + this.age + ' years old');
};
// 测试继承
var childInstance = new Child('Alice', 10);
childInstance.sayName(); // 输出: My name is Alice
childInstance.sayAge(); // 输出: I am 10 years old
这段代码首先定义了一个父类Parent
和它的一个方法sayName
。然后定义了子类Child
,在子类构造函数中调用了父类构造函数,并添加了一个子类特有的方法sayAge
。通过设置Child.prototype
为父类实例,实现了继承,并通过Object.create
确保原型链的正确。最后,我们创建了一个子类的实例,并调用了父类和子类的方法来验证继承机制的有效性。
评论已关闭