gpt4 book ai didi

Javascript:从父( super ?)函数调用子函数。

转载 作者:数据小太阳 更新时间:2023-10-29 03:54:26 25 4
gpt4 key购买 nike

两个父函数都被子函数覆盖。 child 中的两个叫 parent 的两个。但是,我期望在父级别,对一个的调用将调用子方法。有没有我想念的概念?

提前致谢!

http://jsfiddle.net/9mbGN/

function parent(){}

parent.prototype.one = function(){
$('body').append("Parent: one <br/>");
}

parent.prototype.two = function(){
this.one();
$('body').append("Parent: two <br/>");
}


function child(){}

child.prototype = new parent();
child.prototype.constructor = child;

child.prototype.one = function(){ //should this function not be called?
$('body').append('Child: one <br />');
}

child.prototype.two = function(){
$('body').append('Child: do some child stuff here and call parent: <br />');
parent.prototype.two();
}



var k = new child();
k.two();

最佳答案

更优化的方法几乎就像你正在做的那样,但是你通过 this 调用父方法:

child.prototype.two = function(arg1, arg2) {
parent.prototype.two.call(this, arg1, arg2);
};

但是我建议你使用自定义函数来扩展,你可以使用 extend from jsbase

如果您正在使用 ECMAScript 5 getters/setters(如果不只是使用第一个),您可能更喜欢使用 this gist 中的那个。

根据 Dean Edward 的想法,两者可以以相同的方式使用:

var Animal = extend(Object, {

constructor: function(name) {
// Invoke Object's constructor
this.base();

this.name = name;

// Log creation
console.log('New animal named ' + name);
},

// Abstract
makeSound: function() {
console.log(this.name + ' is going to make a sound :)');
},

});

var Dog = Animal.extend({

constructor: function(name) {
// Invoke Animals's constructor
this.base(name);

// Log creation
console.log('Dog instanciation');
},

bark: function() {
console.log('WOF!!!');
},

makeSound: function() {
this.base();
this.bark();
}
});

var pet = new Dog('buddy');
// New animal named buddy
// Dog instanciation
pet.makeSound();
// buddy is going to make a sound :)
// WOF!!!

在您的情况下,它可以是:

var parent = extend(Object, {
one: function() {
$('body').append("Parent: one <br/>");
},
two: function() {
this.one();
$('body').append("Parent: two <br/>");
}
});

var child = parent.extend({
one: function() {
$('body').append('Child: one <br />');
},
two: function() {
$('body').append('Child: do some child stuff here and call parent: <br />');
this.base();
}
});

关于Javascript:从父( super ?)函数调用子函数。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19019287/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com