JS实现子类调用父类的同名函数函数

图像的实现


代码实现

function parent() {
	this.initialize = function() {
		this.x = 1;
		this.y = 1;
	},
	this.initialize()
}function son() {
	this.initialize = function() {
		this.hehe = "hehe";
		this.haha = "haha";
		son.prototype.initialize.apply( this, arguments )
	},
	this.Demo = function(x,y) {
		console.log("son::Demo",  x,  y);
	},
	this.initialize()
}

function Grandson() {
	this.initialize = function() {
		this.kk = "kk";
		son.prototype.initialize.apply( this, arguments )
	},
	this.Demo = function(x,y) {
		Grandson.prototype.Demo.apply( this, arguments ),
		console.log("Grandson::Demo",  x,  y);
	},
	this.initialize()
}

son.prototype = new parent;
Grandson.prototype = new son;

var parent1 = new parent();
var son1 = new son();
var Grandson1 = new Grandson();
Grandson1.Demo(222,333);//  这句话的输出说明了Grandson的成员函数Demo执行时,在内部就会调用父类的son::Demo

结果实现


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
在 JavaScript 中,`super` 方法是用于调用父类方法的关键字。它可以在子类中使用,以便调用父类的构造函数、静态方法和原型方法。使用 `super` 方法可以避免在子类中重复编写父类的代码。 在 ES6 中,使用 `super` 方法要注意以下几点: 1. 在子类的构造函数中,必须先调用 `super()` 方法,以便完成父类的初始化。 2. 在子类的原型方法中,可以使用 `super` 关键字调用父类同名方法。 3. 在子类的静态方法中,也可以使用 `super` 关键字调用父类同名静态方法。 下面是一个简单的示例,演示了如何在子类中使用 `super` 方法: ```javascript class Animal { constructor(name) { this.name = name; } speak() { console.log(this.name + ' makes a noise.'); } } class Dog extends Animal { constructor(name) { super(name); // 调用父类的构造函数 } speak() { super.speak(); // 调用父类同名方法 console.log(this.name + ' barks.'); } } let d = new Dog('Mitzie'); d.speak(); // 输出 "Mitzie makes a noise." 和 "Mitzie barks." ``` 在上面的示例中,`Dog` 类继承自 `Animal` 类。在 `Dog` 类的构造函数中,我们使用 `super(name)` 调用父类的构造函数,并传入了一个参数。在 `Dog` 类的 `speak` 方法中,我们使用 `super.speak()` 调用父类同名方法,并在其后面添加了自己的逻辑。最终,我们创建了一个 `Dog` 对象 `d`,并调用了它的 `speak` 方法,输出了两行信息。第一行信息是来自父类的,第二行信息是来自子类的。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值