javascript从外部作用域变量访问成员函数

javascript accessing a member function from outer scope variable

本文关键字:成员 函数 访问 变量 从外部 作用域 javascript      更新时间:2023-09-26

我一直在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函数是构造函数函数。它旨在创建("构造")自己的实例。为了做到这一点,您需要关键字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;这会奏效的。