基本对象/函数链如何在javascript中工作? [英] How does basic object/function chaining work in javascript?

查看:113
本文介绍了基本对象/函数链如何在javascript中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图将jQuery风格的函数链接在我的脑海中。我的意思是:

I'm trying to get the principles of doing jQuery-style function chaining straight in my head. By this I mean:

var e = f1('test').f2().f3();

我有一个例子可以工作,而另一个没有。我会发布以下内容。我总是想学习第一个原理的基本原理,以便我可以在它之上构建。到目前为止,我只是粗略地了解了链接是如何工作的,而且我遇到了一些我无法智能排除故障的错误。

I have gotten one example to work, while another doesn't. I'll post those below. I always want to learn the first principle fundamentals of how something works so that I can build on top of it. Up to now, I've only had a cursory and loose understanding of how chaining works and I'm running into bugs that I can't troubleshoot intelligently.

我是什么知道:


  1. 函数必须自行返回,又称返回此处;

  2. 可链式函数必须驻留在父函数中,也就是在jQuery中,.css()是jQuery()的子方法,因此jQuery()。css();

  3. 父函数应该返回自身或者它自己的新实例。

这个例子有效:

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();

但这个不是:

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();


推荐答案

在JavaScript中,函数是第一类对象。定义函数时,它是该函数对象的构造函数。换句话说:

In JavaScript Functions are first class Objects. When you define a function, it is the constructor for that function object. In other words:

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();

通过分配

new gmap();

在变量测试中,您现在构建了一个新对象,该对象继承了gmap()构造函数(类)中的所有属性和方法。如果您运行上面的代码段,则会看到添加和删除的提醒。

to the variable test you have now constructed a new object that "inherits" all the properties and methods from the gmap() constructor (class). If you run the snippet above you will see an alert for "add" and "delete".

在上面的示例中,this指的是窗口对象,除非你将函数包装在另一个函数或对象中。

In your examples above, the "this" refers to the window object, unless you wrap the functions in another function or object.

一开始我很难理解链接,至少对我来说是这样,但是一旦我明白了,我意识到它可以是多么强大的工具。

Chaining is difficult for me to understand at first, at least it was for me, but once I understood it, I realized how powerful of a tool it can be.

这篇关于基本对象/函数链如何在javascript中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆