LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Is "new" the only way to initialise an object in Javascript? (https://www.linuxquestions.org/questions/programming-9/is-new-the-only-way-to-initialise-an-object-in-javascript-4175425786/)

resetreset 09-05-2012 11:03 AM

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.

dugan 09-05-2012 11:35 AM

Quote:

Originally Posted by resetreset (Post 4773357)
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#.

resetreset 09-06-2012 01:30 AM

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.

audriusk 09-06-2012 12:37 PM

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. :)

dugan 09-06-2012 03:19 PM

Quote:

Originally Posted by resetreset (Post 4773825)
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.

resetreset 09-07-2012 01:32 AM

Quote:

Originally Posted by audriusk (Post 4774330)
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 (Post 4774330)

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 :)

resetreset 09-07-2012 01:36 AM

Quote:

Originally Posted by dugan (Post 4774433)
* 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.....

audriusk 09-07-2012 03:13 AM

Quote:

Originally Posted by resetreset (Post 4774752)
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 (Post 4774758)
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. :)

resetreset 09-07-2012 09:12 AM

Quote:

Originally Posted by audriusk (Post 4774815)
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 (Post 4774815)

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?

dugan 09-07-2012 09:17 AM

Quote:

Originally Posted by resetreset (Post 4774997)
Btw, what's a good book to learn all the stuff you're talking about?

Javascript: The Good Parts, by Douglas Crockford.

resetreset 09-07-2012 09:28 AM

Oh hey man, you're up and about :)

What time is it for you right now?

dugan 09-07-2012 09:37 AM

7:30 am. I'm in the west coast of Canada.

audriusk 09-07-2012 10:22 AM

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 (Post 4774997)
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 (Post 4774997)
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]);
    }
}


resetreset 09-10-2012 08:59 AM

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.

audriusk 09-10-2012 09:50 AM

Quote:

Originally Posted by resetreset (Post 4776867)
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.


All times are GMT -5. The time now is 02:10 AM.