于是,我翻阅了 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);
},
},
现在,当我尝试在我的_util.template()
函数中调用我的函数时,我set()
当然会得到一个错误,因为this
指向_util
对象而不是template_manager
对象。我看了一下 jQueryextend
方法,我想我明白它在做什么。我的问题是,我是否需要实现我自己的/使用 jQuery 的extend
方法,还是有另一种方法可以让我template_manager
从我的对象中调用_util
对象?
(PS我看过Douglas Crockford关于原型继承的文章,我认为答案就在那里,但恐怕我还没有完全理解。)