<body><script type="text/javascript"> function setAttributeOnload(object, attribute, val) { if(window.addEventListener) { window.addEventListener('load', function(){ object[attribute] = val; }, false); } else { window.attachEvent('onload', function(){ object[attribute] = val; }); } } </script> <div id="navbar-iframe-container"></div> <script type="text/javascript" src="https://apis.google.com/js/platform.js"></script> <script type="text/javascript"> gapi.load("gapi.iframes:gapi.iframes.style.bubble", function() { if (gapi.iframes && gapi.iframes.getContext) { gapi.iframes.getContext().openChild({ url: 'https://www.blogger.com/navbar.g?targetBlogID\x3d6016338663470588542\x26blogName\x3dA+Guide+to+Hell\x26publishMode\x3dPUBLISH_MODE_BLOGSPOT\x26navbarType\x3dBLUE\x26layoutType\x3dCLASSIC\x26searchRoot\x3dhttps://shasini.blogspot.com/search\x26blogLocale\x3den_US\x26v\x3d2\x26homepageUrl\x3dhttp://shasini.blogspot.com/\x26vt\x3d-3621103276626359617', where: document.getElementById("navbar-iframe-container"), id: "navbar-iframe" }); } }); </script>

About

"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt."

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:


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: ,