如何在JavaScript中从子对象调用父对象函数

5

所以,我在阅读 John Resig 的 博客 时,看到了他的 微型模板 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);
        },
    },

现在,当我试图在我的set()函数中调用_util.template()函数时,我当然会出现错误,因为this指向_util对象而不是template_manager对象。我已经研究了jQuery的extend方法,并且我认为我理解它在做什么。我的问题是,我是否需要实现自己的/使用jQuery的extend方法,还是有其他方法可以从我的_util对象调用template_manager对象?(附注:我已经看过Douglas Crockford关于原型继承的article文章,我认为答案在那里,但我恐怕还没有完全理解。)

@Chris,我该好好检查一下。谢谢你发现了这个问题! - Sean Vieira
1个回答

8
您可以使用callapply
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);
    }
}

请参阅"JavaScript绑定情况的解决方法"文章,以获得更加明确的解释。


解决方案有效,并且该文章在更详细地解释范围方面做得非常好。非常感谢Li0liQ! - Sean Vieira

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接