1

I have an object I created in JavaScript. Let's say it looks like this:

function MyObject() {
    this.secretIdea = "My Secret Idea!";
};

MyObject.prototype.load = function() {
    this.MyButton = $(document.createElement("a"));
    this.MyButton.addClass("CoolButtonClass");
    this.MyButton.click = MyButton.onButtonClick;
    someRandomHtmlObject.append(this.MyButton);
};

MyObject.prototype.onButtonClick = function(e) {
    alert(this.secretIdea);
};

As you can see, I have an object setup in JavaScript and, when it's loaded, it creates an anchor tag. This anchor tag as a background image in CSS (so it's not empty).

Now, I understand that the 'this' statement, when the button would actually be clicked, would fall to the scope of the MyButton element rather than the object I have created.

I have tried using call(), try() and bind() and I cannot get this to work. I need it so that, when the button is clicked, it goes back to the object's scope and not the html element's scope.

What am I missing here?

1 Answer 1

1

The this value inside the click event handler refers to the DOM element, not to the object instance of your constructor.

You need to persist that value, also you refer to MyButton.onButtonClick I think you want to refer the onButtonClick method declared on MyObject.prototype:

MyObject.prototype.load = function() {
    var instance = this;
    //..
    this.MyButton.click(function (e) { // <-- looks like you are using jQuery
      // here `this` refers to `MyButton`
      instance.onButtonClick(e);
    });
    //...
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.