且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

基本对象/函数链如何在javascript中工作?

更新时间:2022-04-20 21:20:45

在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.