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

查看:14
本文介绍了基本的对象/函数链在 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();

分配给变量 test,您现在已经构造了一个新对象,该对象继承"了 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"指的是 window 对象,除非您将这些函数包装在另一个函数或对象中.

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

Chaining 起初对我来说很难理解,至少对我来说是这样,但是一旦我理解了它,我就意识到它是一个多么强大的工具.

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天全站免登陆