在JavaScript中创建get/set函数(如jQuery)
Creating a get/set function (like jQuery) in JavaScript
我试图在这个脚本中模拟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
,因此它从未在调用之间保存。
相关文章:
- 执行ajax成功函数-jQUERY
- 函数jquery.html()不提供数据属性集值
- 将变量放入ajax函数JQuery
- 函数jquery的未定义返回
- 如何在嵌套函数jquery上保持变量的值不变
- 用我的函数jquery给出数据/参数
- Firefox在调用函数(jquery)时冻结
- 在传递节时触发一个函数 - jquery
- 循环执行数组函数jQuery
- 在函数中调用另一个函数JQuery
- 对象不是函数-Jquery/JavaScript
- TypeError:对象不是函数-jquery
- 获取函数jQuery设置的属性
- 从函数jquery获取更新的变量值
- 切换而不是悬停函数jQuery
- 函数jQuery.animation()运行了两次行,但不起作用
- 使用函数 jQuery 获取变量
- 自执行函数 jquery 与 JavaScript 的区别
- 从回调函数 -JQuery 获取返回值
- 一个接一个地执行函数 JQUERY