LinuxQuestions.org
Help answer threads with 0 replies.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 09-05-2012, 11:03 AM   #1
resetreset
Senior Member
 
Registered: Mar 2008
Location: Cyberspace
Distribution: Dynebolic, Ubuntu 10.10
Posts: 1,340

Rep: Reputation: 62
Is "new" the only way to initialise an object in Javascript?


I just came across this code:

Code:
that=DHTMLSprite(params) ;
and it's followed by:

Code:
that.moveanddraw = function() { ...whatever

I can't understand it. Isn't there supposed to be a "new" before "DHTMLSprite"? Without it I would have thought that the variable "that" would contain the result of calling the function "DHTMLSprite" with "params" as the parameter.....?



Thanks.
 
Old 09-05-2012, 11:35 AM   #2
dugan
LQ Guru
 
Registered: Nov 2003
Location: Canada
Distribution: distro hopper
Posts: 11,241

Rep: Reputation: 5322Reputation: 5322Reputation: 5322Reputation: 5322Reputation: 5322Reputation: 5322Reputation: 5322Reputation: 5322Reputation: 5322Reputation: 5322Reputation: 5322
Quote:
Originally Posted by resetreset View Post
Without it I would have thought that the variable "that" would contain the result of calling the function "DHTMLSprite" with "params" as the parameter.....?
Uhm, yes. That's what happens. Why is that confusing?

It's also what would happen if DHTMLSprite is called with new. Calling a function with "new" just sets that function's "this" variable to a special value. It's not like C++, Java or C#.

Last edited by dugan; 09-05-2012 at 11:43 AM.
 
Old 09-06-2012, 01:30 AM   #3
resetreset
Senior Member
 
Registered: Mar 2008
Location: Cyberspace
Distribution: Dynebolic, Ubuntu 10.10
Posts: 1,340

Original Poster
Rep: Reputation: 62
I don't follow you at all. Without "new", there is NO OBJECT. So how can "that.moveanddraw = function() { ...whatever" work?

I'm ignoring the 2nd part of your post for now. I don't know C++, Java or C#, so they have no influence on my work.
 
Old 09-06-2012, 12:37 PM   #4
audriusk
Member
 
Registered: Mar 2011
Location: Klaipėda, Lithuania
Distribution: Slackware
Posts: 361

Rep: Reputation: 199Reputation: 199
I am far from expert on JavaScript, nevertheless I'll try to explain, and it's also a good opportunity to refresh my memory on this topic.

DHTMLSprite in your example could be returning an object as follows:
Code:
function DHTMLSprite(params) {
    // Do something with params.
    return {
        // Return an object.
    }
}
So you're not correct claiming that new operator is required to get a new object, because the function above does exactly that -- creates a new object.

Here's how new operator works: it creates a new object which inherits from provided function's prototype. Then that function is called and this inside it is bound to the newly created object. You can modify this by assigning any values to it and even new functions. Note that normally the function used with new does not return a value (though it can, but I'm not sure about the details myself).
Code:
function DHTMLSprite(params) {
    this.foo = params.foo;
    this.bar = params.bar;
    this.somefunc = function () {
        // Do something here.
    };
}

DHTMLSprite.prototype.baz = function (name) {
    return 'Hello, ' + (name ? name : 'world') + '!';
};

somevar = new DHTMLSprite(params);
othervar = somevar.baz();
Also note that if you create multiple DHTMLSprite objects, they would share the same baz function from the prototype, but somefunc would be created for each object from scratch. In other words, defining functions on prototype saves the memory.

Hopefully, I have made things clearer and haven't introduced more confusion to the topic.
 
Old 09-06-2012, 03:19 PM   #5
dugan
LQ Guru
 
Registered: Nov 2003
Location: Canada
Distribution: distro hopper
Posts: 11,241

Rep: Reputation: 5322Reputation: 5322Reputation: 5322Reputation: 5322Reputation: 5322Reputation: 5322Reputation: 5322Reputation: 5322Reputation: 5322Reputation: 5322Reputation: 5322
Quote:
Originally Posted by resetreset View Post
I don't follow you at all. Without "new", there is NO OBJECT.
* takes deep breaths in an attempt to calm down

Okay...

Wherever you got this information, it's not correct. I'd be curious to see a link to it.

Accurate information has been provided by audriusk in this thread, and by me in the thread that you started specifically to ask how the new operator works.

Last edited by dugan; 09-06-2012 at 04:08 PM.
 
Old 09-07-2012, 01:32 AM   #6
resetreset
Senior Member
 
Registered: Mar 2008
Location: Cyberspace
Distribution: Dynebolic, Ubuntu 10.10
Posts: 1,340

Original Poster
Rep: Reputation: 62
Quote:
Originally Posted by audriusk View Post
So you're not correct claiming that new operator is required to get a new object, because the function above does exactly that -- creates a new object.

So, in that DHTMLSprite example, there's an object being returned in the "DHTMLSprite" function?
(I'll have to go check my book).



Quote:
Originally Posted by audriusk View Post

You can modify this by assigning any values to it and even new functions. Note that normally the function used with new does not return a value (though it can, but I'm not sure about the details myself).

OK, this is beyond me for now. I don't really follow what you're saying. But anyway, I'll try and keep it in mind for when my Javascript skills are a bit more than what they are now



Oh by the way I followed your second code example just fine
 
Old 09-07-2012, 01:36 AM   #7
resetreset
Senior Member
 
Registered: Mar 2008
Location: Cyberspace
Distribution: Dynebolic, Ubuntu 10.10
Posts: 1,340

Original Poster
Rep: Reputation: 62
Quote:
Originally Posted by dugan View Post
* takes deep breaths in an attempt to calm down

Okay...

Wherever you got this information, it's not correct. I'd be curious to see a link to it.

Actually in my PAPER book, Javascript Cookbook, it's said that a function can either be made an object of, with new, or can be called as a function. So I naturally got the idea that new was the only way to create an object.....
 
Old 09-07-2012, 03:13 AM   #8
audriusk
Member
 
Registered: Mar 2011
Location: Klaipėda, Lithuania
Distribution: Slackware
Posts: 361

Rep: Reputation: 199Reputation: 199
Quote:
Originally Posted by resetreset View Post
So, in that DHTMLSprite example, there's an object being returned in the "DHTMLSprite" function?
(I'll have to go check my book).
Either that or there's a typo in your book, if DHTMLSprite is really meant to be used as constructor for new operator. The only way to know is to see the source of DHTMLSprite.

Quote:
Originally Posted by resetreset View Post
Actually in my PAPER book, Javascript Cookbook, it's said that a function can either be made an object of, with new, or can be called as a function. So I naturally got the idea that new was the only way to create an object.....
Well, here's the fun part: JS functions already are objects.
Code:
function foo() {
    // Do something here.
}

foo.bar = 42;
foo.baz = 'w00t!';

for (key in foo) {
    if (foo.hasOwnProperty(key)) {
        console.log(key + ' = ' + foo[key]);
    }
}
new creates an entirely new object which also inherits all properties from a prototype of a given constructor function.

And here's the simplest way to create an object:
Code:
foo = {};
It's objects all the way down.
 
Old 09-07-2012, 09:12 AM   #9
resetreset
Senior Member
 
Registered: Mar 2008
Location: Cyberspace
Distribution: Dynebolic, Ubuntu 10.10
Posts: 1,340

Original Poster
Rep: Reputation: 62
Quote:
Originally Posted by audriusk View Post
Either that or there's a typo in your book, if DHTMLSprite is really meant to be used as constructor for new operator. The only way to know is to see the source of DHTMLSprite.

No, you were right. Inside DHTMLSprite there was this:

Code:
var that = {

draw: function (x,y) {

//whatever

},

and later, a

Code:
return that;


I'm guessing "that" is an object. What is the notation they've used above (draw: function)?
Is there any webpage exlaining it? I'm not familiar with it....







Quote:
Originally Posted by audriusk View Post

Well, here's the fun part: JS functions already are objects.
Code:
function foo() {
    // Do something here.
}

foo.bar = 42;
foo.baz = 'w00t!';

for (key in foo) {
    if (foo.hasOwnProperty(key)) {
        console.log(key + ' = ' + foo[key]);
    }
}


I can't follow from "for (key in foo)" onwards. Could you please explain?

Thank God you're closer to my time zone, and I can get the answer quicker than from Dugan

Btw, what's a good book to learn all the stuff you're talking about?
 
Old 09-07-2012, 09:17 AM   #10
dugan
LQ Guru
 
Registered: Nov 2003
Location: Canada
Distribution: distro hopper
Posts: 11,241

Rep: Reputation: 5322Reputation: 5322Reputation: 5322Reputation: 5322Reputation: 5322Reputation: 5322Reputation: 5322Reputation: 5322Reputation: 5322Reputation: 5322Reputation: 5322
Quote:
Originally Posted by resetreset View Post
Btw, what's a good book to learn all the stuff you're talking about?
Javascript: The Good Parts, by Douglas Crockford.

Last edited by dugan; 09-07-2012 at 09:20 AM.
 
Old 09-07-2012, 09:28 AM   #11
resetreset
Senior Member
 
Registered: Mar 2008
Location: Cyberspace
Distribution: Dynebolic, Ubuntu 10.10
Posts: 1,340

Original Poster
Rep: Reputation: 62
Oh hey man, you're up and about

What time is it for you right now?
 
Old 09-07-2012, 09:37 AM   #12
dugan
LQ Guru
 
Registered: Nov 2003
Location: Canada
Distribution: distro hopper
Posts: 11,241

Rep: Reputation: 5322Reputation: 5322Reputation: 5322Reputation: 5322Reputation: 5322Reputation: 5322Reputation: 5322Reputation: 5322Reputation: 5322Reputation: 5322Reputation: 5322
7:30 am. I'm in the west coast of Canada.
 
Old 09-07-2012, 10:22 AM   #13
audriusk
Member
 
Registered: Mar 2011
Location: Klaipėda, Lithuania
Distribution: Slackware
Posts: 361

Rep: Reputation: 199Reputation: 199
Dugan's recommended book is really good. Or at least should be, cause I haven't read it, but I know the author. The guy understands the language really well. When I started using JavaScript for work, my then boss introduced me to Crockford's writings on the net and JSLint tool created by him. There's a concise overview of the language on his website. Probably not the easiest read for beginner, but good nonetheless. It should answer a lot of your questions from this thread (or raise even more ).

Quote:
Originally Posted by resetreset View Post
No, you were right. Inside DHTMLSprite there was this:
Code:
var that = {

draw: function (x,y) {

//whatever

},
and later, a
Code:
return that;
I'm guessing "that" is an object. What is the notation they've used above (draw: function)?
Is there any webpage exlaining it? I'm not familiar with it....
Yes, that is an object. Objects in JavaScript are hashtables (data structures containing key-value pairs). In your example draw: is a key and the (anonymous) function is a value. Below is an example of an object literal:
Code:
foo = {
   bar: 42,        // Key is written as identifier (no quotes).
   'baz': 'xyyzy'  // Key is written as a string.
};

foo['bar'] = null;  // Value is accessed using subscript notation.
foo.baz = 1337;     // Value is accessed using dot notation.

Quote:
Originally Posted by resetreset View Post
I can't follow from "for (key in foo)" onwards. Could you please explain?
Code:
// This for-loop iterates over all the keys in foo object and its prototype chain.
for (key in foo) {
    // Checks if the key belongs to foo itself and doesn't come from prototype chain.
    if (foo.hasOwnProperty(key)) {
        // Outputs the key and its value.
        // console is an object provided by browsers and some other JS runtimes.
        console.log(key + ' = ' + foo[key]);
    }
}
 
Old 09-10-2012, 08:59 AM   #14
resetreset
Senior Member
 
Registered: Mar 2008
Location: Cyberspace
Distribution: Dynebolic, Ubuntu 10.10
Posts: 1,340

Original Poster
Rep: Reputation: 62
Yes, I know of Douglas Crockford too, I downloaded some videos of his on JS from Yahoo YUI theater some years back. Couldn't follow them though, so just left them, and bought some books instead, for the time being. Will go back to the videos, hopefully soon.
I'm still wavering on the notation used - so an object can be defined either as "foo = { bar:42" OR "var x = function foo() { this.bar = 42} "? Is the former, the one you've explained above, what they call JSON?

Thanks for all your help.
 
Old 09-10-2012, 09:50 AM   #15
audriusk
Member
 
Registered: Mar 2011
Location: Klaipėda, Lithuania
Distribution: Slackware
Posts: 361

Rep: Reputation: 199Reputation: 199
Quote:
Originally Posted by resetreset View Post
I'm still wavering on the notation used - so an object can be defined either as "foo = { bar:42" OR "var x = function foo() { this.bar = 42} "? Is the former, the one you've explained above, what they call JSON?
What notion you'll use depends on what you want to achieve. If you want just a single object, the following is fine:
Code:
var foo = {
    bar: 42,
    baz: function () {
        return this.bar;
    }
};

console.log(foo.bar);
console.log(foo.baz());
But if you're planning to have multiple similar objects, and there will be some methods to handle data those objects contain, this is better:
Code:
// Note the capitalized function name, this is often used to
// indicate that it's a constructor function.  This is not required,
// only a convention.
function Foo () {
    this.baz = 42;
}

Foo.prototype.xyyzy = function () {
    return this.baz;
};

var foo = new Foo(),  // foo and bar will inherit from Foo.prototype
    bar = new Foo();  // and hence will share the same methods.

bar.baz = 1337;
console.log(foo.baz);
console.log(bar.xyyzy());
JSON has nothing to do with above (although it is based on a subset of JavaScript language), it's a data serialization format. It is used to store data on disk or transmit it over the network.
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
Can't locate object method "connect" via package "mysql" (perhaps you forgot to load xman fiji Linux - Newbie 9 07-11-2012 08:05 PM
Can't locate object method "splitpath" via package "PACK001" at /usr/lib/perl5/5.8.8/ sajigeorge Linux - Software 1 01-11-2009 06:33 AM
Javascript error "is null or not an object" apt Programming 2 03-28-2005 06:14 AM
samba "Can't initialise locking module - exiting" yoyoguy2 Fedora 3 03-18-2004 09:25 PM
Can't locate object method "splitpath" via package "File::Spec" RobJohnston Linux - General 2 06-28-2003 09:59 AM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 12:42 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration