Writing functionality property (getter and setter) in Javascript Thursday, January 25, 2007 |
When we coding Object-oriented javascript, we simply add 'this' as a prefix before a variable to simulate a property.
It is very simple when we use it in sustained coding:
Quite simple and also leak of functionality, I mean, it only pass a value which we set in previous code and the problem is how we use it to return a various value by a funtion?
Here is the solution:
When we called a variable in javascript, the script engine first call toString function to see if it is defined and returnable, if it is, return the value of toString.
So the code here should be likes this:
Then, we can simply use this.b instead of this.b() and then it will return the value of function b.
It is very simple when we use it in sustained coding:
a = function(){
this.b = 0;
}
alert(new a().b)
Quite simple and also leak of functionality, I mean, it only pass a value which we set in previous code and the problem is how we use it to return a various value by a funtion?
Here is the solution:
When we called a variable in javascript, the script engine first call toString function to see if it is defined and returnable, if it is, return the value of toString.
So the code here should be likes this:
a = function() {
}
a.prototype.b = function(){
return 2;
}
a.prototype.b.toString = function(){
return this.call();
//The 'this' make me a little confused, it doesn't point to the instance we created.
}
//this line added in 4/30/2007
a.prototype.b.valueOf = a.prototype.b.toString;
Then, we can simply use this.b instead of this.b() and then it will return the value of function b.
alert(new a().b);
Labels: coding, javascript