[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 241
  • Last Modified:

Javascript prototype examples

Dear Experts,

After studying prototype of javascript from article tutorial on this site
http://code.tutsplus.com/tutorials/prototypes-in-javascript--net-24949
In that article, it mentions  purpose of prototype will use less memory usage for javascript
if creating many objects like  1000 game objects .In other words, all Game objects can use the same prototype in the function to save memory.

Now I try to create a simple example for tutorial to understand prototype easier.
I try to create a function for restaurant order price calculation according number of food and drink to order. So we need formula in a function for example

function CookMenu(food,drink){
this.price=3100*food+200*drink
return this
}

and I need object for every customer such as

var guest_Bob_price = new CookMenu(2,3);  // guest_Bob_price.price =800

We could NOT change the code of the formula of the function during running besides re-write the code after code running. So if the owner of the restaurant suddenly want to
change CookMenu prices  to   pricechg=300*food+700*drink during applcation code is running , the prototype might be useful to change the internal structure of CookMenu function, Right ?

My question is that
1- How to update Cookmenu function for prototype without creating
many guest customer objects such as 1000 times of  similar "var guest_Bob_price = new CookMenu(2,3);" if I have 1000 different guest or customers ?
2- Could I delete function property such as price when  pricechg prototype property
is created ?  Now guest_Bob_price.price =800 and after change, guest_Bob_price.pricechg =2700. In other words, I want to guest_Bob_price.price =2700 to replace pricechg.

Please read my following CookMenu code for example only and read console.log
and Please advise

Or you can suggest other good tutorial example besides mine that  show a good or best
easy understanding the main purpose of prototype and application examples.

Rwniceing
<!DOCTYPE html>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<head>
<title>Title</title>

<script type="text/javascript">

function CookMenu(food,drink){
	//console.log(CookMenu.prototype.pricechg);//undefined
	if (CookMenu.prototype.pricechg==undefined){
	this.price=100*food+200*drink;
    return this;
	}
}
function start(){
var guest_Bob_price = new CookMenu(2,3);
var guest_John_price = new CookMenu(5,6);

console.log("Bob pay price:", guest_Bob_price.price);
console.log("John pay price:", guest_John_price.price);

//-Menu price might change if input value=1
if (document.getElementById("owner").value==1){
CookMenu.prototype={pricechg:function(food,drink){ return 300*food+700*drink; }};
var owner_restaurant=new CookMenu(2,3);
}

var guest_Bob_price = new CookMenu(2,3);
var guest_John_price = new CookMenu(2,3);
console.log("Bob pay new price:", guest_Bob_price.pricechg(2,3));
console.log("John pay new price:", guest_John_price.pricechg(2,3));
}

</script>
<body onload="start();">
<div>
Prototype javascript tutorial, for example, restaurant menu price change
</div>
<div>
<input type="text" name="owner" id="owner" value="1" />
</div>
</body>
</html>

Open in new window

0
rwniceing
Asked:
rwniceing
  • 10
  • 9
  • 4
2 Solutions
 
RobOwner (Aidellio)Commented:
Ok I would start by reading my article on Javascript classes: http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_12264-Javascript-Frameworks-what-are-they.html

Then follow up on the Mozilla Object Oriented tutorial as they go into more depth on the prototype keyword: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript

Once you understand about creating classes and instantiating them, as well as overriding and adding functions using the prototype keyword, then post back here with any questions you might have.

Rob
0
 
rwniceingAuthor Commented:
Thanks for your reply, I will read it Before that,
instantiating  meaning initializing, Right ?
override meaning overwrite, Right ?
0
 
RobOwner (Aidellio)Commented:
that's right (to both your questions)
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
Ray PaseurCommented:
instantiating  meaning initializing, Right ?
Be careful of the terminology here.  When you create an object from a class, you are creating an instance of the class, hence the term instantiating.  Initializing may have a different meaning, such as setting a variable to a predefined value.
0
 
rwniceingAuthor Commented:
var a;
a=1;

A is initializing to null and then
a=1, a is set to 1.

Right ?

What is different between  both of instantiating and intializing ?
Could you make an example if your last post is correct  ?
0
 
Ray PaseurCommented:
Yes, what you've just illustrated is initializing the variable a with a value of 1.  The variable a now represents an integer, not an object (except in some languages, such as Ruby on Rails).
0
 
rwniceingAuthor Commented:
Could you make a simple  example for instantiating ?
0
 
Ray PaseurCommented:
0
 
rwniceingAuthor Commented:
but it is not  instantiating example , just for object example
0
 
Ray PaseurCommented:
The act of creating an object is called instantiation.  It is a term of art in computer science.
0
 
RobOwner (Aidellio)Commented:
Thanks for clearing that up Ray.
JavaScript is a little different too. You instantiate objects but every class inherits from the object class. I go into more detail in this article.

http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_13138-Javascript-is-just-an-Object.html
0
 
rwniceingAuthor Commented:
And it seems prototype in javascript is similar or same idea of a pointer in  C programming, Right ?
0
 
RobOwner (Aidellio)Commented:
No, not sure where you got that from. Two very different constructs, especially since JavaScript is an interpreted language and C isn't
0
 
RobOwner (Aidellio)Commented:
I have a basic understanding of punters but essentially they are variables that refer to a predefined area of memory (they hold the memory location not the variables value)
I guess that's where you may have got the idea of a pointer. I suppose the principle of the prototype could loosely resemble a pointer but it's giving you the wrong impression. They really shouldn't be compared. Prototype is probably more closely related to an C interface as I understand it, but don't quote me :-)
Think of it more as a way of adding and removing functions and variables on an object in JavaScript
0
 
rwniceingAuthor Commented:
The code following is similar code idea  to quote in the attached link ,http://code.tutsplus.com/tutorials/prototypes-in-javascript--net-24949,  at "Prototype is better" for Game Object.

After I run both for loop code for normal one and prototype one, the prototype one will
run faster since it just create one or only one copy of function() {console.log("it's a bar');}
so that use less memory than creating 10000 function() in normal code.
That is why today's Gaming programming is based on prototype-based javascript, Right ?

Please advise

//-----------------------Normal code
for (var i=0;i<10000;i++) {
    Foo = new Object();
    Foo.bar = function() { console.log('Its a bar'); };

    var x = Foo;
    x.bar();
}
//-----------------Prototype
var Foo = function(){};
Foo.prototype.bar = function(){console.log('Its a bar');};
for (var i=0;i<10000;i++) {
    var x = new Foo();
    x.bar();
}

Open in new window

0
 
RobOwner (Aidellio)Commented:
Yes the prototype code will use less memory, as the 1000 objects will reference the one function.  

However, In the first example, You're essentially creating a copy of the same function 1000 times if you do that within the loop.
0
 
rwniceingAuthor Commented:
question-1, for normal first example code,
So creating 10000 times of function(){} that might not create more memory since the function is same for every times in first example, Right ? OR it will create function() every time and occupy different location memory since every function() memory created is not destroyed unless program is exited.

I believe the first example  will create 10000 function()  different memory location even the function() code is same for every time , that is why prototype example code will run much faster than first example ?

Please advise
0
 
RobOwner (Aidellio)Commented:
that might not create more memory since the function is same for every times in first example, Right ?
This is up to the interpreter (i.e. the browser) and how smart it is when it interprets the code to process it.
Most browsers have task managers built in.  You could use this in conjunction with the local OS task manager to see which way it goes.
Given I have no part in programming any of the browsers you would need to do this to see how it would go.

As for the most efficient way of doing it, I would go with your prototype version as the structure is created first, then the instantiating.  Doing them at the same time would make it difficult for any interpreter to know that it's the same function being created, so i would expect iit to use more memory and be more inefficient than the prototype version.  In a loop, you could just be making one small change to the attached function, based on the index say, that would make each new function unique.
0
 
rwniceingAuthor Commented:
The final answer in following link, may answer the question-1 and question-2
http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_28504085.html#a40282093

Answer to question
1-It is not necessary to create the new object for Bob and John unless you need to
record customer different property such as name, gender,  age....id...,etc.
2- Just use Child OwnerCookMenu() and parent CookMenu() function with prototype as the answer in the link,  Child will inherit all property from parent,  so you can use the same price property and emulate the price override , for example,
pay=OwnerCookMenu.prototype =new CookMenu();
if (document.getElementById("owner").value==1){
OwnerCookMenu.prototype.price= function(food,drink){ return 300*food+700*drink; }
}

Rwniceing
0
 
RobOwner (Aidellio)Commented:
I really think it would be better for you to study object oriented programming. Understand about the reserved keywords etc
All we're doing here is answering one question to ask another
0
 
rwniceingAuthor Commented:
OR suggestion for good tutorial example from the topic post ?
The answer is at this  OOP and Prototype javascript tutorial link at
https://www.youtube.com/watch?v=pu08qQCmw8I 
https://www.youtube.com/watch?v=EBoUT2eBlT4

that is also found in http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_28504085.html#a40282093

People are no patience to complete to read the article because of a lot of terminology or technical term that is not clear enough to state , and so sometimes video tutorial is better than articles

we can say two post have similar questions but not exact same if we go into details

Rwniceing
0
 
rwniceingAuthor Commented:
Thanks for your reply and those article links
0
 
RobOwner (Aidellio)Commented:
Sure I understand that.  It's a long road to understanding this stuff.  Just keep posting new questions on the topics you don't understand and we'll do our best to answer them.  I'm just saying do not neglect any training you can do in this area.  It seems you've got a basic understanding of programming, it would be good for you to refine it.

Please, please take the time to read my article on JS objects as it covers all the topics we've discussed here:

http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_13138-Javascript-is-just-an-Object.html
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 10
  • 9
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now