简体   繁体   中英

javascript accessing a member function from outer scope variable

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.

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.

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 )

Use x=new get_set; That will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM