0

I have a function that I am calling the following way but it returns someVariable.clean is not a function

Here is the code:

var someVariable = function() {
        this.clean = function(obj) {
            alert(obj);
        }
    }

    someVariable.clean('test'); //call

Any idea why it is happening, what am I doing wrong?

5 Answers 5

1

If your're not in ES5 strict mode, you'll add the function .clean() to the global object.

So, just calling clean('test'); would indeed work here. If you want it like you described, you need to return the function an object.

var someVariable = function() {
    return {
        clean: function(obj) {
            alert(obj);
        }
    };
};

If you are in ES5 strict mode, this code would throw an error, since this would be bound to null. What the this context variable is referenced to, always depends on how the function is invoked. In your case, as described, this is either window or null.

It would also work, if you'd invoke your function with the new keyboard:

new someVariable().clean('test');

That is because, new makes the function a constructor function and this is always bound to a newly created object within the function.

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

Comments

1

That is happening because this within the scope of the function is still window (just as it would be if you declared the clean function at the top-level). What you want is:

var someVariable = function() {};
someVariable.clean = function(obj) {
    alert(obj);
}

someVariable.clean('test'); //call

Comments

1

You have forgotten to initialize your prototypical class

new someVariable().clean('test'); 

If you want a flavor of static class then consider using literals:

someVariable = {
    clean: function(obj) {
            alert(obj);
        }
};

Now you can call your way:

someVariable.clean('test');

1 Comment

Thank you, that is very educating! Never heard of EC5 mode.
0

It's not a property of the function. It's only set if you execute the function, and it's then added to the global object (which is still not what you want).

You should instead set it the same way as you call it:

var someVariable = function() {
    // ...
}

someVariable.clean = function(obj) {
    alert(obj);
}

someVariable.clean('test'); // call

Comments

0

Try to do like this for better approch also and to solve your error.

var someVariable = cleanfunction(id); 

function cleanfunction(id)
{          
    clean: function(id) {
        alert(id);          
    }          
}

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.