0

I got this js line:

var functest = function(){
    if (this.href === "undefined") { 
        return window.location 
    } else { 
        return this.href 
    }
};

Basically I want this if function to return the variable necesarry and assign it to functest.

This obviously is not working and returns the function as a string somehow. How should I do this?

11
  • You are making functest the function. To prove this write the following code functest(); this will call the above function and return either the href or the window.location Commented Feb 2, 2014 at 23:31
  • 2
    Question is: Why do you have a function at all? Commented Feb 2, 2014 at 23:33
  • You should use window.location.href, not just window.location Commented Feb 2, 2014 at 23:36
  • 2
    This is incorrect. this.href === "undefined" Drop the quotes this.href === undefined Commented Feb 2, 2014 at 23:37
  • 1
    @zzzzBov: Yep, I agree. An IIFE with a local undefined is a good solution. Commented Feb 3, 2014 at 16:03

3 Answers 3

3

If you want the function to be assigned to a variable that you can call when needed and then you want to assign the return value to a variable:

var functest = function(){if (this.href === "undefined") { return window.location } else { return this.href } };
var funcVal = functest();
Sign up to request clarification or add additional context in comments.

Comments

2

You need to execute the function to assign its return value:

var functest = (function () {
    if (this.href === 'undefined') {
        return window.location;
    } else {
        return this.href;
    }
}());//note the extra parenthesis to call the function

This particular function is probably better written as a single-line ternary assignment:

var functest = this.href === 'undefined' ? window.location : this.href;

Also, you probably wanted to check that this.href === undefined or typeof this.href === 'undefined':

var functest = typeof this.href === 'undefined' ? window.location : this.href;

Comments

1

You can do that with self-executing function like this :

var functest = (function () {
    if (this.href === "undefined") { return window.location } else { return this.href }
})();

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.