Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/454.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何找到方法所属的实例?_Javascript - Fatal编程技术网

Javascript 如何找到方法所属的实例?

Javascript 如何找到方法所属的实例?,javascript,Javascript,//缩小基类代码(如果需要未压缩的代码,我会发布) function Class(){}Class.prototype.construct=function(){};Class.extend=function(c){var a=function(){arguments[0]!==Class&&this.construct.apply(this,arguments)},d=newthis(Class),f=this.prototype;for(var e in c){var b=c[e];if(b

//缩小基类代码(如果需要未压缩的代码,我会发布) function Class(){}Class.prototype.construct=function(){};Class.extend=function(c){var a=function(){arguments[0]!==Class&&this.construct.apply(this,arguments)},d=newthis(Class),f=this.prototype;for(var e in c){var b=c[e];if(b instanceof function)b.$=f;d[e]=b}a.prototype=d;a.extend=this.extend;返回a}

// custom event class
var Event = Class.extend({
    handlers: [],
    // stores the event handler
    subscribe: function(handler, thisObj) {
        this.handlers.push([handler, thisObj]);
    },
    // calls the event handlers
    fire: function() {
        for(i in this.handlers) {
            var handler = this.handlers[i];
            handler[0].apply(handler[1]);
        }
    }
});
var Class2 = Class.extend({
    myEvent: new Event(), // the event
    test: function() { // fires the event
        this.myEvent.fire(this);
    }
});
var Class3 = Class.extend({
    construct: function(model) {
        this.name = "abc";
        model.myEvent.subscribe(this.handler, this); // subscribe to the event
    },
    handler: function() {
        alert(this.name); // alerts 'abc'
    }
});
var instance1 = new Class2();
var instance2 = new Class3(instance1);
instance1.test();

使事件处理程序代码与良好的“this”一起工作的唯一方法是向“subscribe”方法添加一个新参数(“thisObj”)?有更好的方法吗?

您得到的行为是因为当您将“方法”传递给函数时,接收函数不知道它是一个方法。这只是一块需要执行的javascript

Prototype通过
bind
方法解决了这个问题

通过使用闭包,您可以获得类似的行为(我没有查看bind的实现细节)

var Class3 = Class.extend({
    construct: function(model) {
        this.name = "abc";
        //model.myEvent.subscribe(this.handler, this); // subscribe to the event
        var self = this;
        model.myEvent.subscribe(function() {self.handler()});
    },
    handler: function() {
        alert(this.name); // alerts 'abc'
    }
});
或者对自定义事件类的subscribe方法应用一些类似的功能


编辑以反映CMS的观察结果。谢谢

当我在Firefox中运行此代码时,我得到:self.handler不是一个函数。。我将阅读更多关于这些闭包的内容。。看看bind的原型实现。。jQuery还有$.proxy,我想它也有同样的功能,但我正在做一个小项目,它应该独立于任何JavaScript库。无论如何谢谢立即执行的匿名函数将始终具有指向全局对象的
this
值,即
(函数(){returnthis==window;})(;/)如果为true,则不需要该函数,只需分配
var self=this并使用一个简单的匿名函数(如您返回的函数)执行
self.handler()
。我不知道匿名函数的第一部分有
这个
引用全局对象。很高兴知道。谢谢