JavaScript继承是一种面向对象编程的概念,它允许一个对象(子类)继承另一个对象(父类)的属性和方法。在JavaScript中,继承可以通过原型链和构造函数来实现。
Parent.prototype.sayHello = function() {
console.log("Hello, I am " + this.name);
}
function Child() {
this.name = "Child";
}
Child.prototype = new Parent();
var child = new Child();
child.sayHello(); // 输出:Hello, I am Child
```
Parent.prototype.sayHello = function() {
console.log("Hello, I am " + this.name);
}
function Child() {
Parent.call(this); // 调用父类的构造函数
this.name = "Child";
}
var child = new Child();
child.sayHello(); // 报错:child.sayHello is not a function
```
Parent.prototype.sayHello = function() {
console.log("Hello, I am " + this.name);
}
function Child() {
Parent.call(this); // 调用父类的构造函数
this.name = "Child";
}
Child.prototype = new Parent(); // 继承父类的方法
var child = new Child();
child.sayHello(); // 输出:Hello, I am Child
```
var parent = {
name: "Parent",
sayHello: function() {
console.log("Hello, I am " + this.name);
}
};
var child = createObject(parent);
child.name = "Child";
child.sayHello(); // 输出:Hello, I am Child
```
var parent = {
name: "Parent"
};
var child = createObject(parent);
child.name = "Child";
child.sayHello(); // 输出:Hello, I am Child
```
Parent.prototype.sayHello = function() {
console.log("Hello, I am " + this.name);
}
function Child() {
Parent.call(this); // 调用父类的构造函数
this.name = "Child";
}
// 优化父类的实例创建过程
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
var child = new Child();
child.sayHello(); // 输出:Hello, I am Child
```
推荐的腾讯云相关产品和产品介绍链接地址:
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云