473,673 Members | 2,564 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

constructing vs prototyping

Hey all,

What are the pros and cons of defining methods in the constructor vs
through the prototype? For example:

Constructing:
-------------
function MyObj()
{
this.MyMethod = function() {};
}

Prototyping:
------------
function MyObj() {}
MyObj.prototype .MyMethod = function() {};

Currently, I'm of the mindset that the former method is preferable in
all situations except where you don't have access to the constructor
(e.g. adding to Object or Array or whatnot). Part of my reasoning is
personal preference for how the code looks, but what really got me
started coding with the former method was my switch to using closures.
I use closures to keep an object reference even in event handlers, by
beginning every object with a "var self = this;" line. The problem with
prototype functions being that they don't have the closure.

So,

-------
function MyObj()
{
var self = this;
self.msg = 'Hello World';
self.toString = function() {return self.msg};
}
alert(new MyObj);
-------

works, but

-------
function MyObj()
{
var self = this;
self.msg = 'Hello World';
}
MyObj.prototype .toString = function() {return self.msg};
alert(new MyObj);
-------

does not. From that basic advantage of defining a method in the
constructor, it's a quick appeal to consistency to arrive at the
conclusion that it's the preferred method overall.

In summary, it appears to me that defining a method in the constructor
gives you every advantage of prototyping the method, except one: you
can prototype a method in without access to the constructor code. On
the other hand, prototyping has the bigger disadvantage of not being
able to use the forementioned closure. Well, at least *I* think it's a
bigger disadvantage. Plus I like the "containedn ess" of defining
functions within the constructor, vs. the sprawl of prototyping.

So what am I missing?

Lance

Jul 23 '05 #1
1 1806
cainlevy wrote:
What are the pros and cons of defining methods in the constructor vs
through the prototype?
I've answered this before:
<URL:http://groups.google.c o.uk/groups?selm=EJV 1e.7128%24Ab.28 71%40text.news. blueyonder.co.u k>

[snip]
Currently, I'm of the mindset that [...] method [definition during
instantiation] is preferable in all situations [...]
I would disagree. If you don't need to create a closure, or
unnecessarily priviledge a method, then don't.

[snip]
Part of my reasoning is personal preference for how the code looks
Whilst aesthetically pleasing code is nice, I don't think it's a reason
for doing something where a better alternative exists.

[snip]
function MyObj()
{
var self = this;
self.msg = 'Hello World';
self.toString = function() {return self.msg};
}
This is a very bad example. No closure is necessary as the following
code is precisely the same.

function MyObj() {
this.msg = 'Hello World';
}
MyObj.prototype .toString = function() {return this.msg;};

A better example would have been:

function MyObj() {
var msg = 'Hello World';

this.toString = function() {return msg;};
}

where a closure /is/ necessary.

[snip]
Plus I like the "containedn ess" of defining functions within the
constructor, vs. the sprawl of prototyping.


I fail to see how

function MyObj() {
}
MyObj.method = function() {/* ... */};

could be considered sprawling when compared to

function MyObj() {
this.method = function() {/* ... */};
}

However, I would consider excessive method definition within the
constructor to be poor form as you'd start to obscure the important
details of instantiation.

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #2

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

Similar topics

30
2754
by: Dave Allison | last post by:
Oh no, not another "check out my cool new language" posting :-) For about 5 years now, I have been developing a scripting/prototyping language that is now available on the net. It's called Aikido and was born in Sun Labs, but has been released as open source. I no longer work for Sun, but am continuing to use and develop it. The language has a syntax similar to C++ and Java but is aimed at adhoc and prototyping tasks. Unlike other...
9
2670
by: Carl | last post by:
I have been using Python for quite some time now and I love it. I use it mainly for explorative computing and numerical prototyping, ie testing and trying out different kinds of algorithms and computational schemes. The use of Python as my first-choice language has made me extremely productive. Now, I have always believed that Python is a poor performer in terms of numerical speed. My experience, however, is that the efficient use of...
1
2371
by: Will | last post by:
function obj1() { this.children; this.Children = function() { if(typeof(this.children) === 'undefined') { this.children = new col(); } return this.children; }
4
1267
by: Jeff Thies | last post by:
It seems to me that document.getElementById and document.all are essentially the same thing. I'm thinking of prototyping document.getElementById for those browsers that understand document.all but not document.getElementById (IE4). Is that a reasonable thing to do? Suggestions? Jeff
13
1691
by: rs | last post by:
Dear All, I have a question regarding proptypes for functions. What is the recommended practice? The way I do it is to put all my external functions in a header file, while protyping internal (file scope) functions at the start of the source file. I've seen many people (especially using gcc under linux) don't botehr prototyping internal functions but just declare them inline so to speak.
4
2220
by: Tilted | last post by:
Does anyone here use prototyping tools? I'm building one myself as I feel like I'm doing the same thing over and over again with the majority of my projects, how do people generally feel about them? Do people ever use the generated code in production? Thoughts appreciated. Chris.
1
1677
by: matt.rasmus | last post by:
I have been using python for the last two years to create various visualizations for my research in computational biology. Over the years, I found that I often needed the same kinds of features for many of my visualizations (OpenGL graphics with basic scrolling and zooming). I have implemented these features in an extension module for python called SUMMON which I have made freely available on my website for anyone who is interested...
2
3313
by: ChrisO | last post by:
I've been pretty infatuated with JSON for some time now since "discovering" it a while back. (It's been there all along in JavaScript, but it was just never "noticed" or used by most until recently -- or maybe I should just speak for myself.) The fact that JSON is more elegant goes without saying, yet I can't seem to find a way to use JSON the way I *really* want to use it: to create objects that can be instantated into multiple...
1
2296
by: kardon33 | last post by:
Ok I have a problem when i try to install a perl extension that was a converted C header file using h2xs. My problem starts after i run "perl Makefil.PL" when i try to run "nmake". I get the fallowing error in my command prompt. Please specify prototyping behavior for ArtNet2.xs (see perlxs manual) cl -c -I. -nologo -GF -W3 -MD -Zi -DNDEBUG -O1 -DWIN32 -D_CONSOLE 'cl' is not recognized as an in operable program or batch...
0
8508
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8953
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
8652
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
8704
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...
1
6264
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5727
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
4253
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...
0
4448
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2849
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

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.