Geu*_*uis 26 javascript methods method-chaining chaining
我正试图让jQuery风格的函数链接在我的脑海中.我的意思是:
var e = f1('test').f2().f3();
Run Code Online (Sandbox Code Playgroud)
我有一个例子可以工作,而另一个没有.我会发布以下内容.我总是想学习第一个原理的基本原理,以便我可以在它之上构建.到目前为止,我对链接的工作方式只有一个粗略而宽松的理解,而且我遇到了一些我无法智能排除故障的错误.
我知道的:
这个例子有效:
var one = function(num){
this.oldnum = num;
this.add = function(){
this.oldnum++;
return this;
}
if(this instanceof one){
return this.one;
}else{
return new one(num);
}
}
var test = one(1).add().add();
Run Code Online (Sandbox Code Playgroud)
但是这个没有:
var gmap = function(){
this.add = function(){
alert('add');
return this;
}
if(this instanceof gmap) {
return this.gmap;
} else{
return new gmap();
}
}
var test = gmap.add();
Run Code Online (Sandbox Code Playgroud)
Lar*_*ark 38
在JavaScript中,函数是第一类对象.定义函数时,它是该函数对象的构造函数.换一种说法:
var gmap = function() {
this.add = function() {
alert('add');
return this;
}
this.del = function() {
alert('delete');
return this;
}
if (this instanceof gmap) {
return this.gmap;
} else {
return new gmap();
}
}
var test = new gmap();
test.add().del();
Run Code Online (Sandbox Code Playgroud)
通过分配
new gmap();在变量测试中,您现在构建了一个新对象,该对象"继承"了gmap()构造函数(类)中的所有属性和方法.如果您运行上面的代码段,则会看到"添加"和"删除"的提醒.
在上面的示例中,"this"指的是窗口对象,除非您将函数包装在另一个函数或对象中.
起初我很难理解链接,至少对我来说是这样,但是一旦我理解了它,我就意识到它可以是多么强大的工具.