简体   繁体   English

javascript 从外部 scope 变量访问成员 function

[英]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..我一直在 jsfiddle 中尝试一些 js 代码,似乎我无法让下面的所有这些代码组合工作..

//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您要么必须创建一个新的get_set实例

var x = new get_set();

or inside get_set you have to use return this;或者在get_set你必须使用return this; for this example to work.让这个例子工作。

Your get_set function is a constructor function.您的get_set function 是构造函数function。 It's intended to create ('construct') instances of itself.它旨在创建(“构造”)自身的实例。 In order to make that work you need the keyword new .为了完成这项工作,您需要关键字new So所以

var getset = new get_set;

creates an instance of get_set.创建 get_set 的实例。 Now the methods getset.set and getset.get are available.现在可以使用getset.setgetset.get方法。

In this case maybe you could create a unique instance using an Object literal:在这种情况下,也许您可以使用 Object 文字创建一个唯一实例:

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 )现在您不需要new关键字并且方法可以立即使用( get_set.getget_set.set

Use x=new get_set;使用 x=new get_set; That will work.那可行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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