[英]accessing methods in JavaScript object
Consider the following Java script code: 考虑以下Java脚本代码:
var myObj = function ( ) {
var x = 0;
return {
addup: function (y) {
x += y;
},
getX: function ( ) {
return x;
}
}
}();
This function returns an object with two methods (if I am not wrong). 此函数使用两种方法返回对象(如果我没记错的话)。
now, two questions: 现在,有两个问题:
thanks, 谢谢,
myObj.getX();
and myObj.addup(5);
和myObj.addup(5);
Example - http://jsfiddle.net/qWT9N/ 示例-http://jsfiddle.net/qWT9N/
how can I call the two methods returned from the function? 如何调用函数返回的两个方法?
myObj.addup(10);
var xValue = myObj.getX();
can those methods still have access to the variable x ? 这些方法仍然可以访问变量x吗? Yes 是
You've created "template" object myObj
with private x
propery and two public methods. 您已经使用私有x
属性和两个公共方法创建了“模板”对象myObj
。
To create object based on your "template" call var obj = myObj();
要基于“模板”创建对象,请调用var obj = myObj();
obj.addup(2);
您可以像obj.addup(2);
那样称呼它们obj.addup(2);
and obj.getX();
和obj.getX();
x
variable from them 是的,那些方法可以从中访问Private x
变量
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.