如何从javascript中的子对象调用父对象函数
因此,我在阅读John Resig的blog,看到他的micro-templating javascript engine,并决定尝试实现我自己的JavaScript模板管理系统,以加深对原型继承的理解。然而,当我开始写它时,我遇到了一个问题。如何从javascript中的子对象调用父对象函数
要开始了,这是我的基本代码:
function template_manager() { };
template_manager.prototype = {
tags: {},
templates: {},
output: {},
default_template: "default",
set: function (tags, template_name) {
template_name = "Greetings!";
//template_name = this._util.template(this.nothing, this.default_template);
console.log(template_name);
},
get: function(tags, template_name) {
console.log("Getting");
},
unset: function(tags, template_name) {
console.log("Removing");
},
render: function(template_name) {
console.log("Rendering");
},
//_util goes here
};
// Take it for a quick test drive.
test = new template_manager;
test.set();
test.get();
test.unset();
test.render();
然后,我开始对一些常见的代码工作,我决定把它变成一个实用对象:
_util: {
// Used to set the default values for optional arguments
optional: function(obj, def_value) {
return (typeof obj === "nothing") ? obj : def_value;
},
template: function(template_name) {
return this._util.optional(template_name, this.default_template);
},
},
现在,当我尝试呼叫我的_util.template()
函数时,我的set()
函数当然会得到一个错误,因为this
指向的是_util
对象而不是template_manager
对象。我看了一下jQuery extend
方法,我认为我明白它在做什么。我的问题是,我是否需要来实现我自己的/使用jQuery的extend
方法,还是有另一种方法让我从我的_util
对象中调用template_manager
对象?
(PS我看了看原型继承道格拉斯Crockford的article,我认为答案是有的,但是我怕我不完全理解它。)
您可以使用call
或apply
即
template_manager.prototype = {
set: function (tags, template_name) {
template_name = "Greetings!";
template_name = this._util.optional.call(this, this.nothing, this.default_template);
console.log(template_name);
}
}
该解决方案的工作原理和文章做得非常出色,可以更详细地解释范围。非常感谢Li0liQ! – 2010-03-03 22:11:00
@Sean Vieira,不客气。 – Li0liQ 2010-03-03 22:13:14
@Chris,为我提供了无需双重检查的权利。感谢您的支持! – 2010-03-03 22:01:39