0

I want to send the selector value to the prototype. Currently i am using

var selector; //id of html element
function $(selector)
{
    if(window===this)
        return new $(selector);
    return this;
}
$.prototype={
    tooltip: function(){
        console.log(selector);
        //do calculations with the selector value
        return this;
    }
};

It is showing undefined.

Is there any way to pass variable?

1
  • And where are you calling .tooltip? Commented Jun 10, 2013 at 15:13

2 Answers 2

3

No, you cannot access it from the prototype methods. The selector parameter is a local variable to the constructor.

However, you can make it available as a property on your instance:

function $(selector) {
    if(!(this instanceof $))
        return new $(selector);

    this.selector = selector; // assigns the variable to a property
}
$.prototype.tooltip = function(){
    console.log(this.selector); // access the property on the instance
    //do calculations with the selector value
    return this;
};
Sign up to request clarification or add additional context in comments.

Comments

1

I don't see where you are calling any of your functions or setting selector. However, one problem is that the formal function parameter selector in your definition of $ masks the outer variable also named selector. If you eliminate the function parameter, it should work better (assuming that you are also somewhere setting selector):

var selector; //id of html element
function $()
{
    if(window===this)
        return new $(selector);
    return this;
}
$.prototype={
    tooltip: function(){
        console.log(selector);
        //do calculations with the selector value
        return this;
    }
};

The way your code is written now, it is as if it were written as follows:

var selector; //id of html element
function $(x)
{
    if(window===this)
        return new $(x);
    return this;
}
$.prototype={
    tooltip: function(){
        console.log(selector);
        //do calculations with the selector value
        return this;
    }
};

2 Comments

No, eliminating the constructor function parameter will definitely not help the prototype method…
@Bergi - It depends on what OP expects the constructor to be. If inside the constructor OP wants to access the global variable selector, then it definitely will help.

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.