Sea*_*ira 5 javascript jquery prototype extend
所以,我正在阅读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();
Run Code Online (Sandbox Code Playgroud)
然后我开始研究一些常用代码,我决定把它放到一个实用程序对象中:
_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);
},
},
Run Code Online (Sandbox Code Playgroud)
而现在,当我尝试在我的_util.template()函数中调用我的函数时,我set()当然会得到一个错误,因为this指向_util对象而不是template_manager对象.我看一下jQuery extend方法,我认为我理解它在做什么.我的问题是,我是否需要实现自己的/使用jQuery的extend方法,还是有另一种方法让我template_manager从_util对象中调用对象?
(PS我看过Douglas Crockford 关于原型继承的文章,我认为答案就在那里,但我恐怕还没有完全理解它.)
你可以使用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);
}
}
Run Code Online (Sandbox Code Playgroud)
有关更明确的说明,请参阅"从JavaScript中获取绑定情境"一文.
| 归档时间: |
|
| 查看次数: |
5927 次 |
| 最近记录: |