0

I have been trying out some js code in jsfiddle and it seems I cant get all these combinations of codes below to work..

//combination #1    
function get_set() {
    this.get = function () {
        document.write("get");
    };
    this.set = function () {
        document.write("set");
    };
};

var x = get_set; // storing function reference in x
x.get(); //invoking doesnt work.

//combination#2
var get_set = function() {
    this.get = function () {
        document.write("get");
    };
    this.set = function () {
        document.write("set");
    };
};

get_set.get(); //doesnt work as well..

Is there something that I miss? Thanks in advance for constructive suggestion/pointing out any errors. Would appreciate any help.

3 Answers 3

4

You either have to create a new instance of get_set

var x = new get_set();

or inside get_set you have to use return this; for this example to work.

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

2 Comments

The return this part is not good advice. If called without new, this will be the global/window object so this.get assigns a function to a global variable called get and similarly for this.set.
Additionaly, returning this from a function call doesn't create unique instances. So if this is returned, in var a=get_set(), b=get_set(); b.set = 'I have changed' a.set now also has the value 'I have changed'
3

Your get_set function is a constructor function. It's intended to create ('construct') instances of itself. In order to make that work you need the keyword new. So

var getset = new get_set;

creates an instance of get_set. Now the methods getset.set and getset.get are available.

In this case maybe you could create a unique instance using an Object literal:

var get_set = {
    get: function () {
        document.write("get");
    },
    set: function () {
        document.write("set");
    }
};

Now you don't need the new keyword and the methods are available right away (get_set.get, get_set.set)

2 Comments

Perhaps, but now the OP can't make instances of get_set, but maybe that isn't needed anyway.
Hi RobG, it was a suggestion. I changed the wording of my answer a little bit.
0

Use x=new get_set; That will work.

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.