繁体   English   中英

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

[英]javascript accessing a member function from outer scope variable

我一直在 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..

有什么我想念的吗? 提前感谢您的建设性建议/指出任何错误。 将不胜感激任何帮助。

您要么必须创建一个新的get_set实例

var x = new get_set();

或者在get_set你必须使用return this; 让这个例子工作。

您的get_set function 是构造函数function。 它旨在创建(“构造”)自身的实例。 为了完成这项工作,您需要关键字new 所以

var getset = new get_set;

创建 get_set 的实例。 现在可以使用getset.setgetset.get方法。

在这种情况下,也许您可以使用 Object 文字创建一个唯一实例:

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

现在您不需要new关键字并且方法可以立即使用( get_set.getget_set.set

使用 x=new get_set; 那可行。

暂无
暂无

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

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