0

I'm having some Javascript woes, lets say we have a constructor

function test(element) {
  this.element = element;
  this.element.onfocus = function() { this.onfocus(); }
}

test.prototype.onfocus = function() {
  alert("focused");
}

new test(document.getElementByID("E1"));

So I am trying to dynamically set the focus event inside the constructor, but it doesn't seem to work, and I can't figure it out.

Anyone help?

Thanks,

AJ

2 Answers 2

1

In JavaScript, and in the context of this.element.onfocus = function() {this.onfocus(); }, second this is the element who fired the event.

In other words, your code should be like this if you want to work in a proper way:

function test(element) {
  this.element = element;

  var currentObject = this;
  this.element.onfocus = function() {currentObject.onfocus(); }
}

Don't think JavaScript is a decent object-oriented programming language, as it's prototype-oriented and it has some weak things like one that's affecting your code.

Why don't you read this article? I belive it'll clarify this keyword for you:

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks very much, this works great, I will take your advice and read the article as well.
It's not about doing spam, but maybe you're interested in some OOP implementation I did for JavaScript and it works like a charm, as I'm using in some personal projects I'm going to release to the open source community: joopl.codeplex.com.
1

You must store a reference to 'this', because the onfocus function is in another context and the 'this' refers to something else:

function test(element) {
  this.element = element;
  var that = this;
  this.element.onfocus = function() { that.onfocus(); }
}

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.