简体   繁体   English

具有自身引用的Javascript函数对象

[英]Javascript function object with this reference to itself

I can't seem to find an example of what I'm trying to achieve, although I'm sure it has been done many times before... 我似乎找不到我要实现的目标的示例,尽管我确信它已经做过很多次了……

I want to create an object which will have a set of properties and member functions but that I can also call directly. 我想创建一个具有一组属性和成员函数的对象,但是我也可以直接调用它。 In the same way the jQuery object allows you to call $("selector") or $.method(...) 以相同的方式,jQuery对象允许您调用$("selector")$.method(...)

Here's a slimmed down version of what I'm trying to achieve : 这是我要达到的目标的简化版本:

var foobar = function(param) {
    return "FOO : " + this.lookup(param);
}

foobar.vals = {
    1: "one",
    2: "two"
};

foobar.lookup = function (param) {
    return "BAR : " + this.vals[param];
}

foobar.lookup("1")
// returns "BAR : one"

foobar("1")
// returns error since 'this' points to global scope
// I'd want it to return "FOO : BAR : one"

I've also tried various approaches with function prototype but can't seem to find a method which gives me everything I want... 我还尝试了使用函数原型的各种方法,但似乎找不到能够提供我想要的一切的方法...

var foobar = function(param) {
    return "FOO : " + foobar.lookup(param);
}

will return you what you want 会给你你想要的

To understand this, maybe you should take a look at the basics of JavaScript. 要理解这一点,也许您应该看一下JavaScript的基础知识。 What are functions how to instanciate an object and what are objects... 什么是函数来实例化一个对象,什么是对象...

To get something like JQuery this is not very difficult, the JQuery main object is simply a function which also has "static" functions. 要获得类似JQuery的东西并不是很困难,JQuery主对象只是一个具有“静态”功能的函数。

to declare a variable as function you do 将变量声明为函数

var myFunc = function(){};

to use the variable and extend it with static stuff you simply assign it via 使用变量并将其扩展为静态内容,您只需通过

myFunc.staticFunc = function(){};

this doesn't mean that myFunc.staticFunc can be accessed with this in any instance of myFucn because you didn't add the function to the prototype... 这并不意味着在myFucn的任何实例中都可以使用此函数访问myFunc.staticFunc,因为您没有将函数添加到原型中。

To define a class like object which can be instanciated you also define it as function and then extend the prototype. 要定义可以实例化的类之类的对象,您还可以将其定义为函数,然后扩展原型。 Prototype is your class definition which is used to construct the object's instance: 原型是您的类定义,用于构造对象的实例:

myFunc = function(){
  // ctor
  this.lala = "blub";
} ;

myFunc.prototype.objectFunc = function() { 
   return this.lala;
}

now the object myFunc has a function objectFunc. 现在,对象myFunc具有函数objectFunc。 I have to initialize it with new... 我必须用新的初始化它...

alert(new myFunc().objectFunc());

instances can access itself with this... 实例可以用这个来访问自己

To do something like jquery you'll have to do some tricks. 要执行类似jquery的操作,您将需要做一些技巧。 Your global variable must be a function which returns an instance of your "real" object, which can implement whatever... 您的全局变量必须是一个返回“真实”对象实例的函数,该对象可以实现任何...

Then you can call your variable as if it is a function, eg myFunc()... 然后,您可以像对待函数一样调用变量,例如myFunc()...

Hope the following example makes it more clear how this works: ( can be found on jsfiddle ) 希望下面的示例可以更清楚地说明其工作原理:( 可以在jsfiddle上找到

(function ($) {

    var myRealObj = function (outId, printText) {
        this.text = printText;
        $("#" + outId).append("<li>" + this.text + "</li>");
    };

    myRealObj.prototype.objectFunc = function () {
        return this.lala
    };

    var myFunc = function (out, txt) {
        return new myRealObj(out, txt);
    };

    myFunc.someFunc = function () {
        myFunc("out", "myFunc.someFunc got called");
    };

    myFunc.static = {};
    myFunc.static.someFunc = function () {
        myFunc("out", "myFunc.static.someFunc got called");
    };


    window.$$ = myFunc;
})($);

$$("out", "test obj function");
$$.someFunc();
$$.static.someFunc();

You could add: 您可以添加:

foobar = foobar.bind(foobar);

to make the variable refer to a bound version of the function. 使变量引用函数的绑定版本。 Any call to the (updated) "foobar" would have this bound to the original function object. 对(更新的)“ foobar”的任何调用都将把this绑定到原始函数对象。 You'd also have to mirror the properties if you wanted to get at them directly, which is sort-of a mess. 如果要直接获取属性,还必须镜像属性,这有点混乱。

In the jQuery implementation, there's a separate internal function that handles the basic routing of the master $() function. 在jQuery实现中,有一个单独的内部函数来处理主$()函数的基本路由。

Note also that the "global" $.whatever() functions don't really have much to do with the set of methods supported by jQuery instances (objects returned from the $() function). 还要注意,“全局” $.whatever()函数实际上与jQuery实例(从$()函数返回的对象)支持的方法集无关。 The $ object just serves as a namespace so that those global utilities don't pollute the global (window) namespace. $对象仅用作命名空间,这样那些全局实用程序就不会污染全局(窗口)命名空间。

声明var foobar = function(param) {...在全球范围内所以this将永远是一个window

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM