473,786 Members | 2,462 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Functions Within Objects

If I do this:

function MyObject() {
this.MyFunc = function () {alert("MyFunc called");}
}

obj1 = new MyObject();
obj2 = new MyObject();

do I get two copies of the code inside MyFunc?
Aug 12 '05 #1
6 1473
On 12/08/2005 14:52, Vic Sowers wrote:
function MyObject() {
this.MyFunc = function () {alert("MyFunc called");}
}

obj1 = new MyObject();
obj2 = new MyObject();

do I get two copies of the code inside MyFunc?


Yes. Each time the MyObject constructor is called, the inner function
expression will be evaluated anew, creating separate function objects.
This is why 'prototyped' methods are preferable when feasible.

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Aug 12 '05 #2


Vic Sowers wrote:
If I do this:

function MyObject() {
this.MyFunc = function () {alert("MyFunc called");}
}

obj1 = new MyObject();
obj2 = new MyObject();

do I get two copies of the code inside MyFunc?


ECMAScript allows for some optimization but neglecting that each time
you do new MyObject() indeed each created "instance" gets its own
function object as this.myFunc.

But you should simply code
function MyObject () {

}
MyObject.protot ype.MyFunc = function () {alert("MyFunc called");
that way all "instances" share that single function object but due to
the prototype chain set up you can then use e.g.
var obj1 = new MyObject();
obj1.MyFunc();
--

Martin Honnen
http://JavaScript.FAQTs.com/
Aug 12 '05 #3

Martin Honnen wrote:
Vic Sowers wrote:
If I do this:

function MyObject() {
this.MyFunc = function () {alert("MyFunc called");}
}

obj1 = new MyObject();
obj2 = new MyObject();

do I get two copies of the code inside MyFunc?


ECMAScript allows for some optimization but neglecting that each time
you do new MyObject() indeed each created "instance" gets its own
function object as this.myFunc.

But you should simply code
function MyObject () {

}
MyObject.protot ype.MyFunc = function () {alert("MyFunc called");
that way all "instances" share that single function object but due to
the prototype chain set up you can then use e.g.
var obj1 = new MyObject();
obj1.MyFunc();
--

Martin Honnen
http://JavaScript.FAQTs.com/


I have a question about this. If you're adding lots of methods to a
prototype, is there a significant difference between these two
constructs?

MyObject.protot ype.method1 = function () { ... }
MyObject.protot ype.method2 = function () { ... }

MyObject.protot ype = {
method1: function () { ... },
method2: function () { ... }
}

Thanks in advance,
Ian

Aug 12 '05 #4

"Martin Honnen" <ma*******@yaho o.de> wrote in message
news:42******** **************@ newsread2.arcor-online.net...


Vic Sowers wrote:
If I do this:

function MyObject() {
this.MyFunc = function () {alert("MyFunc called");}
}

obj1 = new MyObject();
obj2 = new MyObject();

do I get two copies of the code inside MyFunc?


ECMAScript allows for some optimization but neglecting that each time you
do new MyObject() indeed each created "instance" gets its own function
object as this.myFunc.

But you should simply code
function MyObject () {

}
MyObject.protot ype.MyFunc = function () {alert("MyFunc called");
that way all "instances" share that single function object but due to the
prototype chain set up you can then use e.g.
var obj1 = new MyObject();
obj1.MyFunc();


OK, what I really want is:

function MyObject(arg) {
var private = arg;
this.public = 0;
MyFunc = function () {return private*this.pu blic);
}

obj1 = new MyObject(2);
obj1.public = 3
alert(obj1.MyFu nc());
obj2 = new MyObject(3);
obj1.public = 3
alert(obj1.MyFu nc());

Any suggestions?
Aug 13 '05 #5


Ian Osgood wrote:

If you're adding lots of methods to a
prototype, is there a significant difference between these two
constructs?

MyObject.protot ype.method1 = function () { ... }
MyObject.protot ype.method2 = function () { ... }

MyObject.protot ype = {
method1: function () { ... },
method2: function () { ... }
}


Yes, the first approach with each assignment adds a function property (a
method) to the existing prototype object while the second approach
replaces the existing prototype object with a new object which has two
function properties.
So any assigment using the second approach complete destroys any
previous assignments.

--

Martin Honnen
http://JavaScript.FAQTs.com/
Aug 13 '05 #6


Vic Sowers wrote:

OK, what I really want is:

function MyObject(arg) {
var private = arg;
this.public = 0;
MyFunc = function () {return private*this.pu blic); I guess you want
this.MyFunc = .. }


If you want to have something like private members in JavaScript 1.x
then the suggested way to achieve that is using an inner function and
exploiting closures as above but you need then to be aware that indeed
any creation of new MyObject() creates its own inner function object so
that approach is much more memory intensive as using public members and
share methods as function properties of the prototype. It is up to you
to decide how much objects you need te create and whether private
members are improving your code.

--

Martin Honnen
http://JavaScript.FAQTs.com/
Aug 13 '05 #7

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

Similar topics

18
8740
by: vrillusions | last post by:
I've been using functions since I first started using php, but I've been hearing more and more about classes, which I never really looked at that much. I understand the whole OO programming aspect, but are there any advantages to having classes as opposed to just functions? I've heard that the classes are better because they only load the functions they need to, where with an include file of functions, the whole page gets loaded, even if...
12
7421
by: bissatch | last post by:
Hi, Generally if I re-use code, I use a function. If I need to use these functions over a number of pages I write the function to an include file where all pages have access. So when should I ever use PHP classes instead. I have learned how to put together PHP classes but never seen a reason to use them where I can simply use a function.
5
3349
by: hokiegal99 | last post by:
A few questions about the following code. How would I "wrap" this in a function, and do I need to? Also, how can I make the code smart enough to realize that when a file has 2 or more bad charcters in it, that the code needs to run until all bad characters are gone? For example, if a file has the name "<bad*mac\file" the program has to run 3 times to get all three bad chars out of the file name. The passes look like this:
99
5925
by: David MacQuigg | last post by:
I'm not getting any feedback on the most important benefit in my proposed "Ideas for Python 3" thread - the unification of methods and functions. Perhaps it was buried among too many other less important changes, so in this thread I would like to focus on that issue alone. I have edited the Proposed Syntax example below to take out the changes unecessary to this discussion. I left in the change of "instance variable" syntax (...
9
1968
by: relaxedrob | last post by:
Howdy All! I am still getting my head around a few base concepts. Any comments or criticisms on the below definitions would be most welcome! A function is an object. JavaScript objects have properties: - a var (which is an object or a primitive); - a method (which is a function assigned to the object).
1
1610
by: optimistx | last post by:
How to build or find an object browser for javascript? E.g. Delphi integrated developement environment ('ide') offers a very practical object browser for Pascal language. When typing a name with a dot you get a list of objects,properties and methods to select from. When you select or type a methodname or function and the left parenthesis , the system writes the possible argument types. With key F1 one gets thorough description of the...
11
3363
by: tshad | last post by:
I am setting up some of my functions in a class called MyFunctions. I am not clear as to the best time to set a function as Shared and when not to. For example, I have the following bit manipulation routines in my Class: ******************************************************************************* imports System NameSpace MyFunctions
14
6027
by: Jess | last post by:
Hello, I learned that there are five kinds of static objects, namely 1. global objects 2. object defined in namespace scope 3. object declared static instead classes 4. objects declared static inside functions (i.e. local static objects) 5. objects declared at file scope.
13
2533
by: JohnQ | last post by:
The implementation of classes with virtual functions is conceptually easy to understand: they use vtables. Which begs the question about POD structs: how are they associated with their member functions in common implementations? And where is the 'this' ptr tucked away at for POD structs with member functions? John
4
4882
by: =?ISO-8859-15?Q?Jean=2DFran=E7ois?= Lemaire | last post by:
Hello all, I'm learning C and I still am struggling to understand some basic concepts. For example, I read in the standard that with functions such as strcpy, 'If copying takes place between objects that overlap, the behavior is undefined.' But how can I be sure that they don't overlap? For example, if I write this: char string1 = "overlap";
0
9496
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
10363
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...
0
10164
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8989
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...
1
7512
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
6745
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
5397
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
5534
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2894
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.