在JavaScript中创建get/set函数(如jQuery)

Creating a get/set function (like jQuery) in JavaScript

本文关键字:函数 jQuery set JavaScript 创建 get      更新时间:2023-09-26

我试图在这个脚本中模拟jQuery风格的getter/setter。我知道我可以从responseText函数中获取_text变量并使其工作,但我不明白为什么我目前拥有的不工作。

是否可以将_text变量保留为responseText函数的私有变量,并让该函数像我希望的那样工作?

我这儿有把小提琴:http://jsfiddle.net/brxaetty/

代码:

var responseText = function(text) {
    var _text = 'goodbye world';
    var _responseText = function(response) {
        if (response) {
            _text = response;
        } else {
            return _text;
        }
    };
    if (text) {
        _responseText(text);
    } else {
        return _responseText(text);
    }
}
console.log(responseText()); //should be goodbye world
responseText('hello world'); //should set _text to hello world
console.log(responseText()); //should say hello world, does not

var responseText = function(text) {
    var _text = 'goodbye world';
    return function(response) {
        if (response) {
            _text = response;
        } else {
            return _text;
        }
    };
}();
console.log(responseText()); //should be goodbye world
responseText('hello world'); //should set _text to hello world
console.log(responseText()); //says hello world

我在这里所做的是创建一个闭包,将_text保持在该闭包中,然后返回一个函数。此函数位于闭包内部,并引用了_text,能够正常工作。

(要查看代码段的控制台输出,请参阅我的MSE功能请求和用户脚本:向堆栈代码段添加控制台)

在您的原始代码中,每次都要重新创建_text,因此它从未在调用之间保存。