简体   繁体   English

从另一个对象的方法调用对象的原型方法

[英]Calling an object's prototype method from another object's method

I am trying to create a simple callback system that would fire upon hitting a button. 我正在尝试创建一个简单的回调系统,该系统将在按下按钮时触发。 Rather than the callback being a factory function, it is a prototype method of a different object. 回调不是工厂函数,而是其他对象的原型方法。 I've gotten it to work but I don't understand it. 我已经开始使用它了,但是我不理解。 Why do I need to use .bind(object) to get the object to fire its method? 为什么我需要使用.bind(object)来使对象触发其方法? Originally I tried no bind, and then bind(this), which both failed. 最初我没有尝试绑定,然后尝试bind(this)都失败了。

function Bar() {}

Bar.prototype = {
    getStuff: function () {
        return "Hello";
    },

    setStuff: function () {
        console.log( this.getStuff() );
    }
}

function Foo() {
    this.afterSubmit = null;
    var self = this;
    $('button').click(function () {
        self.submit()
    });
    return this;
}

Foo.prototype = {
    submit: function () {
        if (this.afterSubmit !== null) {
            this.afterSubmit();
        }
        $('#msg').append('clicked ');
        return this;
    },

    setAfterSubmit: function (callback) {
        this.afterSubmit = callback;
        return this;
    }
}

var bar = new Bar();
var foo = new Foo().setAfterSubmit(bar.setStuff.bind(bar));
// Why do I need to bind bar ?

Please take a look at my fiddle https://jsfiddle.net/j5qfuzna/ 请看看我的小提琴https://jsfiddle.net/j5qfuzna/

this.afterSubmit();

This is setting the context to the Foo instance. 这是将上下文设置为Foo实例。 Binding it to the Bar instance prevents that from happening. 将其绑定到Bar实例可以防止这种情况的发生。

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

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