473,667 Members | 2,568 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to do Prototype-based OO in JavaScript?

I've heard that JavaScript is a prototype-based language instead of a
class based one. I'm interested in learning the prototype-based
paradigm of OO programming, but I am unsure of the best way to use
JavaScript as a prototype-based language. I'm stuck between two ways
and both methods might be right (or wrong).

Method 1:

/* create an Animal "object" */
function Animal() {} ;

/* "copy" the animal object to a new object mouse */
var mouse = new Animal();

/* create a method to the animal */
Animal.prototyp e.speak = function() { alert('squeak!' ); };
mouse.speak(); /* alerts squeak! */

Method 1 doesn't really feel like it's true prototype-based because I
need to instantiate it using 'new' instead of cloning an object like
Io or Self. So I created a second method that just uses JavaScript
objects, which to me, feels a bit more prototype-based.

Method 2:
/* create an Animal object */
var Animal = {}; // same as var Animal = new Object();

/* "copy" the animal object to a new object mouse */
var mouse = Animal;

/* create a method to the animal */
Animal.speak = function() { alert('squeak!' ); };
mouse.speak(); /* alerts squeak! */

There's also a method three which basically combines both methods.
function Animal() {};
var mouse = new Animal();
mouse.speak = function() { alert('squeak!' ); };
mouse.speak();

But if I use method 3, I wouldn't know why I created an empty Animal
function if I was going to dynamically add new methods to the objects
it instantiated. So based on the 3 methods above (or an entirely new
method) which simulates prototype-based programming in JavaScript?
Thanks.

May 29 '07 #1
7 1525
Hi,
Isn't prototype-based programming also called instance-based
programming?

May 29 '07 #2
On May 29, 11:53 am, jangc...@gmail. com wrote:
I've heard that JavaScript is a prototype-based language instead of a
class based one. I'm interested in learning the prototype-based
paradigm of OO programming, but I am unsure of the best way to use
JavaScript as a prototype-based language. I'm stuck between two ways
and both methods might be right (or wrong).

Method 1:

/* create an Animal "object" */
function Animal() {} ;

/* "copy" the animal object to a new object mouse */
var mouse = new Animal();

/* create a method to the animal */
Animal.prototyp e.speak = function() { alert('squeak!' ); };
mouse.speak(); /* alerts squeak! */

Method 1 doesn't really feel like it's true prototype-based because I
need to instantiate it using 'new' instead of cloning an object like
Io or Self. So I created a second method that just uses JavaScript
objects, which to me, feels a bit more prototype-based.
The above makes all Animals squeak.
Method 2:
/* create an Animal object */
var Animal = {}; // same as var Animal = new Object();

/* "copy" the animal object to a new object mouse */
var mouse = Animal;

/* create a method to the animal */
Animal.speak = function() { alert('squeak!' ); };
mouse.speak(); /* alerts squeak! */
So does method 2, but nastier:

var Animal={};
var Mouse=Animal;
var Cat=Animal;
Cat.Eats='mouse s(sic)';
alert(Mouse.Eat s); // ouch!

There's also a method three which basically combines both methods.
function Animal() {};
var mouse = new Animal();
mouse.speak = function() { alert('squeak!' ); };
mouse.speak();
FWIW...

function Animal(){};
/* Don't know what type of animal I am so... */
Animal.prototyp e.speak=functio n(){alert('*gri m silence*')};

function Mouse(){};
Mouse.prototype =new Animal();
/* I'm a generic mouse so... */
Mouse.prototype .speak=function (){alert('squea k!')};

function Cat(){};
Cat.prototype=n ew Animal();
/* Not a cat person, so they can keep quiet */

var foo=new Animal();
var tom=new Cat();
var jerry=new Mouse();
var mortimer=new Mouse();
mortimer.speak= function()
{
alert("I can talk! Where's the cheese?")
};

foo.speak();
tom.speak();
jerry.speak();
mortimer.speak( );

----
Geoff

May 29 '07 #3
On May 29, 1:11 pm, Geoffrey Summerhayes <sumr...@gmail. comwrote:
So does method 2, but nastier:

var Animal={};
var Mouse=Animal;
var Cat=Animal;
Cat.Eats='mouse s(sic)';
alert(Mouse.Eat s); // ouch!
Yikes, ouch is right.

I found another method by more researching. It's using Crockford's
function for prototypical inheritance.

Object.prototyp e.clone = function() {
function TempClass() {};
TempClass.proto type = this;
return new TempClass();
}

Animal = {};
var Mouse = Animal.clone();
var Cat = Animal.clone();
Cat.eats = 'mouses';
alert(Mouse.eat s); // Not ouch.

/* and using your example */
Animal.speak = function() { alert('*grim silence*'); };
var Mouse = Animal.clone();
Mouse.speak = function() { alert('squeak!' ); };
var Cat = Animal.clone();
Cat.speak = function() { alert('hiss!'); };

var foo = Animal.clone();
var tom = Cat.clone();
var jerry = Mouse.clone();
var mortimer = Mouse.clone();
mortimer.speak = function() { alert("I can talk! Where's the
cheese?"); };

foo.speak();
tom.speak();
jerry.speak();
mortimer.speak( );

I kind of like this method better. I guess I don't like that 'new'
keyword in JavaScript which makes me think that I'm not dealing with
objects like a true prototype-based language. It feels like I'm still
dealing with Classes.

May 29 '07 #4
On May 30, 1:53 am, jangc...@gmail. com wrote:
I've heard that JavaScript is a prototype-based language instead of a
class based one. I'm interested in learning the prototype-based
paradigm of OO programming, but I am unsure of the best way to use
JavaScript as a prototype-based language. I'm stuck between two ways
and both methods might be right (or wrong).
[...]
Method 2:
/* create an Animal object */
var Animal = {}; // same as var Animal = new Object();

/* "copy" the animal object to a new object mouse */
var mouse = Animal;
That doesn't "copy" the Animal object, it creates a second reference
to the same object. When the right hands side of an assignment is an
object, it's pseudo-code is "assign a reference to...".
--
Rob
May 29 '07 #5
On Tue, 29 May 2007 at 08:53:14, in comp.lang.javas cript, wrote:
>I've heard that JavaScript is a prototype-based language instead of a
class based one. I'm interested in learning the prototype-based
paradigm of OO programming, but I am unsure of the best way to use
JavaScript as a prototype-based language. I'm stuck between two ways
and both methods might be right (or wrong).

Method 1:

/* create an Animal "object" */
function Animal() {} ;

/* "copy" the animal object to a new object mouse */
var mouse = new Animal();

/* create a method to the animal */
Animal.prototy pe.speak = function() { alert('squeak!' ); };
mouse.speak( ); /* alerts squeak! */

Method 1 doesn't really feel like it's true prototype-based because I
need to instantiate it using 'new' instead of cloning an object like
Io or Self. So I created a second method that just uses JavaScript
objects, which to me, feels a bit more prototype-based.
<snip>

Javascript is not like conventional prototype-based languages. You don't
create an object by cloning from a 'prototype' object.

Forget Io and Self; javascript is different!

John
--
John Harris
May 29 '07 #6
ja******@gmail. com wrote:
I've heard that JavaScript is a prototype-based language instead of a
class based one.
You heard right. Objects can inherit from objects.

var animal = {
speak: function () {
alert('Hello, world!');
}
};
var mouse = animal.beget();
mouse.speak();

See http://javascript.crockford.com/prototypal.html
May 30 '07 #7
On May 29, 7:28 pm, Douglas Crockford <nos...@sbcglob al.netwrote:
jangc...@gmail. com wrote:
I've heard that JavaScript is a prototype-based language instead of a
class based one.

You heard right. Objects can inherit from objects.

var animal = {
speak: function () {
alert('Hello, world!');
}
};
var mouse = animal.beget();
mouse.speak();

Seehttp://javascript.croc kford.com/prototypal.html
With this beget system if you have many animals to produce and have to
name them all you wouldn't want to write like the following
(especially if there were more properties to set)

var mouse = animal.begat();
mouse.name = "Harold";
var cat = animal.begat();
cat.name = "Martha";
....

It would be much handier to have a function that automates this

function makeAnimal(name ) {
var a = animal.begat();
a.name = name;
return a;
}
var mouse = makeAnimal("Har old");
var cat = makeAnimal("Mar tha");

and now here I am back at the same issue of having a constructor but
one that is is less efficient (download time, construction time) then
JavaScript's native constructor:

function Animal(name) {
this.name = name;
}
Animal.prototyp e.speak = function(){...} ;

var mouse = new Animal("Harold" );
var cat = new Animal("Martha" );

What is the big gain from begat()?

Thanks,
Peter

May 30 '07 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
1239
by: Florian Loitsch | last post by:
hi, in section 10.1.8 (Arguments Object) it is stated that the "internal ] property of the arguments object is the orginal Object prototype object, the one that is the *initial* value of Object.prototype". Furthermore the Object.prototype property has attributes . My question now: what does the "initial" refer to? To the untouched prototype-object, or to the current Object.prototype? In the latter case: why would the write "initial", if...
8
2056
by: Robert | last post by:
Hi, I can use "with" like this: function MyObject(message) { this.message = message; } function _MyObject_speak() {
21
3837
by: Rob Somers | last post by:
Hey people, I read a good thread on here regarding the reason why we use function prototypes, and it answered most of my questions, but I wanted to double check on a couple of things, as I am writing something up on functions, and I don't like writing about things I am not sure about. Ok, then, here we go: I initially thought that one would only really need to use a function
23
2429
by: Allin Cottrell | last post by:
Thomas Heinz wrote (in re. gcc compilation of this erroneous program): $ cat test.c int f(int); int f(); int f() {return 0;} int main (void) { return 0; }
13
2556
by: eman1000 | last post by:
I was recently looking at the prototype library (http://prototype.conio.net/) and I noticed the author used the following syntax: Object.extend(MyObj.prototype, { my_meth1: function(){}, my_meth2: function(){} }); to define new methods on the MyObj prototype object. Object.extend
6
1481
by: mmcloughlin | last post by:
I'm learning about objects and am trying to figure out how basic inheritance works. I've got into the habit of explicitly setting the prototype object with an object literal as it seems to make the creation of a class easier to read/understand. Anyway it seems to break the inheritance chain in the following code and I don't know why. window.onload = function() {
5
2233
by: Daz | last post by:
Hi everyone. My query is very straight forward (I think). What's the difference between someFunc.blah = function(){ ; } and
2
9716
by: jaysome | last post by:
While looking at the source code for gcc today, I noticed that a prototype for main() was declared. From gcc.c: extern int main (int, const char **); int main (int argc, const char **argv) { ....
5
3583
by: ziobudda | last post by:
Hi, I want ask you if, for a web portal/application, is better prototype or Jquery? I don't want to innesc some type of flame, but after the announce that drupal use JQuery and that the new Wordpress 2.2 use Jquery I ask myself if my choice of use prototype.js is the bettere choice. M. Sorry for my bad english.
2
6458
by: hzgt9b | last post by:
I know how to overwrite a function. Normally this is what I would do: function someFunction() { /* orig definition here */ } //later in the execution stream I would do... someFunction = function () { /* overwrite function definition */ } The above works fine for me even when someFunction is originally defined in a seperate frame other than the code that overwrites it (obviously on the same domain). What I don't know how to-do is...
0
8365
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8883
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8563
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8646
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7390
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5675
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4200
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2776
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2013
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.