Results 1 to 2 of 2

Thread: what can achieve with 'prototype' in plain javascript can do with

  1. #1
    Join Date
    Jan 2012
    Posts
    74
    Thanks
    10
    Thanked 0 Times in 0 Posts

    Default what can achieve with 'prototype' in plain javascript can do with

    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

  2. #2
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    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:

    Code:
    <!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:

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

    Code:
    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);
    	}
    }
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •