I’m a comer at JavaScript, and just learning some basic stuff (function, variable, etc) and I don’t know so much about complex structure in JavaScript.
When I read the source code of one of the web applications, there is a big point that I cannot understand. Here’s the code :
Helper.using('py.Figures' , function (ns) {
ns.Point = function (params) {
ns.Figure.call(this, params);
this.setType('Point');
this.visual(new Kinetic.Circle({
radius:5, strokeWidth:2,
fill:'red', stroke:'black',
draggable:false
}));
this.getX = function () {
};
this.getY = function () {
};
this.getPosition = function () {
return {
x:this.getX(), y:this.getY()
}
}
ns.Point.distance = function (p1, p2) { // some code }
ns.MidPoint = function (params) { // some code }
};
1) First point that I don’t know in above code is the first line declaration :
Helper.using('py.Figures' , function (ns) {... } );
Many files in this document use this structure. In this document, there is a file name Helper, but when I search in this document, I don’t see some thing like py.Figures (by using Control + F). So, what does it really points to?
Above line looks something like a function, so what does function(ns) mean in this, it looks like parameter, but I don’t think so.
2) The second point I don’t know is :
ns.Point, ns.Point.distance, ns.MidPoint look like methoda. So, function(ns) is a class, right ? And if ns.Point is a method, why in this method, there are other methods like getX and getY and it makes me feel that those look like a class too.
Sorry if my question is silly, but this code looks strange to me, and I don’t see anything familar with some language I have learnt (Java, C#), or another scripting language too (Python)
Thanks.
1) That
function (ns) {... }is indeed an argument. The function is parsed, and the pointer to the function is passed to the functionHelper.using. You won’t see these thing in Java, but I think it’s one of the awesome points of Javascript.It’s the usual way to define callbacks, and that argument function looks like a callback indeed.
2) No,
nsis a class object, or better, is generically anObject. It doesn’t need to be an instance of a class. Then the callback function defines the methodPointon the objectns. In the body of the method, it defines (or maybe redefines) the methodsgetX,getYandgetPosition, becausethisrefers to the objectns.On a second look,
ns.Pointis indeed a function, but it may serve as a class definition, so in other parts of the code you may notice something likenew ns.Point(...). That’s how “classes” work in Javascript.