我有一个像这样的脚本(JS)
function Quick () {
this.getById = function (id) {
return document.getElementById(id);
}
this.doSomethingElse = function () {
return Quick.getById('test').nodeName;
}
}
如何在同一个函数中调用.getById()'快速' (在另一个this.x函数中)?
从外面我会称之为
var x = new Quick();
x.getById('someid');
但是我不认为我应该在同一个函数中声明一个新的函数实例。
答案 0 :(得分:2)
<强> jsBin demo 强>
function Quick () {
this.getById = function(id) { // use: = function(id) {
return document.getElementById(id);
};
this.doSomethingElse = function(id) { // pass the desired 'id' argument and
return this.getById(id).nodeName; // Use the this reference
};
}
如果您对可链接性感兴趣 and want to do something like:
x.getById('test').getNodeName();
// Get this ^^ guy and do this ^^
您可以做的是:
function Quick () {
var el; // internal variable
this.getById = function(id) {
el = document.getElementById(id);
return this; // To keep your Methods chainable
};
this.getNodeName = function() {
console.log( el.nodeName );
return this; // To keep your Methods chainable
};
}
var x = new Quick();
x.getById('test').getNodeName(); // "DIV"
答案 1 :(得分:0)
模块模式更适合您的要求
var Quick = {
getById: function(id) {
return document.getElementById(id);
},
doSomethingElse: function () {
return Quick.getById('test').nodeName;
}
}