PDA

View Full Version : what can achieve with 'prototype' in plain javascript can do with



lse123
01-06-2012, 02:35 PM
Basically what can achieve with 'prototype' in plain javascript can do with, 'this.property' or 'this.method' inside the object declaration?

Yes same exactly thing / No differ

jscheuer1
01-06-2012, 04:55 PM
It (this) points to the instance, but depending upon execution time and/or scope, a variable may need to be set ahead of time to the instance. However, in its simplest form:


<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script>
function myfunction(string){
this.string = string;
this.blab();
}

myfunction.prototype = {
blab: function(){
alert(this.string);
}
}
</script>
</head>
<body>
<script>
new myfunction('Hello World!');
</script>
</body>
</html>

Using this.property (this.string) is fine.

Adding a this.method within the prototype object:


function myfunction(string){
this.string = string;
this.preblab();
}

myfunction.prototype = {
preblab: function(){
this.string = this.string.toUpperCase();
this.blab();
},

blab: function(){
alert(this.string);
}
}

But like I say, if the timing (or anything else for that matter) brings it out of scope, a variable must be assigned ahead of time:


function myfunction(string){
this.string = string;
this.preblab();
}

myfunction.prototype = {
preblab: function(){
this.string = this.string.toUpperCase();
this.blab();
},

blab: function(){
var instance = this;
setTimeout(function(){alert(instance.string);}, 3000);
}
}