A Delphi programmer like me, accustomed with strongly typed programming, with clear function block limitation and with classic object oriented style, finds JavaScript overwhelmingly weird. In JavaScript a variable type is interpreted and can happily jump from one type to another, object oriented is based on prototyping starting from the Object primitive type and functions are objects derived from Object.
The Object type has two properties (constructor, prototype) and six methods (eval, toSource, toString, unwatch, valueOf, watch) (see here).
Function is a type descended from Object and has six more properties (arguments, arguments.callee, arguments.caller, arguments.length, arity, length) and two methods (apply, call) (see here).
Below are some code snippets:
Creating an object is as follows:
var myObject = new Object();
or
var myObject = { }
In the second notation, the members of the object are expressed like name:value pairs as:
var myObject = { aname : 15, bname: "test" }
Such a member can be a function like:
var myObject = { myfunc: function(msg){ return msg+msg; } }
A function can be created also as follows:
var f = new Function("a","b","return a+b;");
To create a simple object is used the special keyword this:
function myType(a,b,c){
this.a=a;
this.b=b;
this.c=c;
}
Then you can use this object like:
var f = new myType(10," and ",20);
document.write(f.a + f.b + f.c); // The result is 10 and 20
Create an object with a method:
function myType(a,b){
this.a=a;
this.b=b;
this.add = function(){ with(this) return a+b; }
}
Now use the object:
f = new myType(5,6);
document.write(f.add()); // The result is 11
document.write(f.add()); // The result is 11
Note that the add method is present in any object created and if there are 1000 instances of myType, there are also 1000 instances of the function add. To avoid this, use the prototype keyword like this:
function myType(a,b){
this.a=a;
this.b=b;
}
myType.prototype.add = function(){ return this.a + this.b; }
Use it like previously explained:
f = new myType(19,11);
document.write(f.add()); // The result is 30
document.write(f.add()); // The result is 30
There can be created a helper function like:
Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;
};
this.prototype[name] = func;
return this;
};
The simple object:
function myType(a,b){
this.a=a;
this.b=b;
}
Add a new method like this:
myType.method("add", function(){ return this.a+this.b; });
Then use it as usual:
f = new myType(125,80);
document.write(f.add()); // The result is 205
document.write(f.add()); // The result is 205
This is enough to get started with objects for now.




Niciun comentariu:
Trimiteți un comentariu