Is "new" the only way to initialise an object in Javascript?
ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
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.....?
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#.
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.
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.
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
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
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.....
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
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.
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
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'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
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
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]);
}
}
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?
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.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.