(function).prototype 是如何工作的?

How does (function).prototype work exactly?

我正在通读 How to Make a Javascript Library,我遇到了作者所说的一点:

    function _() {
        //Some obects and variables and junk. . .
}

_.prototype = {
    //some code. . .
    myFunction: function() {
        //Bla bla bla. . .
    }
}

我想知道它是如何工作的,它有什么作用。我知道它创建了 _.myFunction() 命令,但我不明白如何创建。我想知道这是否是唯一的方法,是否需要在某处包含一些其他全局变量。

提前致谢!

编辑:试验它是如何工作的,我发现了以下内容:

function _$() {
    //Bla bla bla. . . 
}
_$.prototype {
    myFunc: function(foo) {
        return foo;
    }
}

然后,当我调用 _$.myFunc 时,我得到:Unkown Syntax error: myFunc is not a function 正如 Felix King 所说,它不可用。谁能告诉我为什么,以及如何使我设置的 myFunc 的功能可以通过 _$.myFunc(null);

访问

此处正在修改对象 __.prototype 属性。您可以阅读更多关于 prototype modification/method 加法 here.

Adding properties or methods to the prototype property of an object class makes those items immediately available to all objects of that class, even if those objects were created before the prototype property was modified.

我想出了我想要做的事情。 Prototype简单来说就是对象内部的对象类型,参考this.

第二部分,我想做的是设置一些可以被 _$.function(args) 访问的东西 通过实验发现的方法是:

var _$ = function() {
    //args and variables etc. . .
};
_$.myFunc = function(args) {
    return args;
}

然后,_$.myFunc(5) returns: 5

尽管问题已在一年前得到解答,但我认为值得分享,这样可能会有所帮助 reader。

function _() {
        //Some obects and variables and junk. . .
        // missing like was 
        return this;

}

_.prototype = {
    //some code. . .
    myFunction: function() {
        //Bla bla bla. . .
    }
}

上面代码中唯一的混淆是'_',因为javascript的命名准则说"any variable or function can start with _"。如果我这样写代码:

 function Blah() {
            //Some obects and variables and junk. . .
            return this;
    }

  Blah.prototype = {
        //some code. . .
        myFunction: function() {
            //Bla bla bla. . .
        }
    }

现在我想每个人都可以使用或了解如何使用它。像 Joke().myFunction().

所以我认为这里的混淆是“_”。