So this is more of a question due to "not knowing the right word, thus I can't google it up" (I think).
What I have been wondering with javascript. One can create two "types" of Objects.
One would be: (or through using prototypes)
function Foo(){
this.bar = function(){};
}
var foo = new Foo();
The other one being:
var foo = {
bar : function(){}
};
The only few differences that I can come up with would be the fact that the former uses prototypes and can "extend" from other objects and also allows multiple instances where the latter can only have one instance and can't be extended (in the same way) (correct me if I am wrong)
However, in this case the variable named var foo has the exact same properties in both cases.
So for a concrete question: what is the name of the type of object being created (how can I search for more information on google for it) in the latter version and what differences are there between the two ways of creating an object?
The differences you are describing are correct.
The latter is called object literal notation and is more concise if you just want to create one object. But they are not two different types of objects. The object literal notation is more like a shortcut (but preferred) for creating objects.
You might want to read MDC - Working with objects.
The literal notation is actually the same as doing:
var foo = new Object();
foo.bar = function() {};
but as already said, it is more concise and easier to read.
Update:
Maybe one further difference worth mentioning: Calling new Foo() does not necessarily mean you will get a "Foo object" back. A constructor function can return any object. E.g. this is valid:
function Foo() {
return new Bar();
}
var foo = new Foo(); // foo contains a "Bar object"
This can become useful for inheritance or if you want to e.g. cache instances and return the same instance for the same parameters passed to the function.
When you define an object using:
var foo = {};
It is literal. That object is an instant instance of the object. When you define an object like:
function Foo(){
this.bar = function(){};
}
There is no instance created until you do new Foo().
Related
I have noticed I can create the same object using a constructor in two different ways.
var myObj = Object()
var myObj = new Object()
I can add properties to both using these methods. myObj.age = 1 and myObj['age'] = 1. The properties of both can be accesed the same way.
So what is the actual difference between these two ways I created myObj? Also is one of these the better way to create an object?
The difference is that the first one simply calls Object() as a function, within the scope of the window object.
The second one actually instantiates a new object. It's the one you want to use to create an object.
The difference may not be obvious with the Object() function, but let's say you create your own type, like so:
function User(name) {
this.name = name;
}
var u1 = User("John");
var u2 = new User("Jane");
console.log(u1); // *undefined* because `User()` doesn't return anything.
console.log(this.name); // John
console.log(window.name); // John
console.log(u2.name); // "Jane"
The Object function itself is a special case--it does create a new Object. But since most functions don't work that way, it's good to get in the habit of using the new keyword when instantiating things. If you're just creating a plain old Object, on the other hand, most people prefer the more concise syntax:
var myObj = {};
The first statement is a function call, meaning that myObj will get whatever is returned in the Object() function. As it happens, the function Object() will provide you with a reference to an Object object, whereas 'normal' constructors will not.
See f.e. the following:
function O(){
this.bla= "bla";
return this;
}
Calling O() here will yield a reference to window, not to an instance of O.
I know JavaScript inheritence is much different than typical OO languages (Java, c++, etc.). Searching around, there also seems to be many different ways to create classes and class hierarchies. Because of this I'm confused about JavaScript inheritence.
Given the following code
if (!com) var com = {};
if (!com.foobar) com.foobar = {};
com.foobar.Foo = {
foo : "foo",
bar : "bar",
baz : function () {
return true;
}
};
Why is the following not allowed? Why is com.foobar.Foo not a constructor? Is it because Foo is not a function, but an object?
var baz = new com.foobar.Foo();
Since I cannot do the above, how would I create a new Foo?
If I want to extend Foo, I thought I would do this:
var bar = Object.create(com.foobar.Foo, {buz: {value: "neat"}});
.. but is bar a subtype of Foo or an instance of Foo? I'm leaning towards instance of Foo because the following prints 'undefine'
console.log(bar.prototype);
You're correct, you can't do var baz = new com.foobar.Foo(); because Foo is an object, not a function.
Object.create is used to set the prototype of a variable (i.e. bar.prototype = Object.create(/*etc etc*/)). For more information, see the MDN page: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create
Using Object.create properly results in bar being another object with the prototype of Foo. This means that anything Foo has can be used on bar, eg bar.bar === 'bar' (if that makes sense). Changes to Foo will be reflected in bar, but not the other way around. It's not quite a subtype. (JS is weird, but it's delightfully so.)
For more on this, check out MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript
Javascript has no classes, only objects. When you create an object, it can also have a prototype, which is just another object that the created object will use to delegate calls to properties (or functions) it doesn't itself understand.
This works more or less like classic inheritance, since subclasses also delegate calls it doesn't understand to superclasses.
So, taking that lead, you'd like to make Foo a prototype for other objects you create; Foo would act somewhat like a superclass to the objects.
A handy function you already know about is the Object.create. You can use it to create a new object with a specific prototype, as you did:
var bar = Object.create(com.foobar.Foo, {buz: {value: "neat"}});
This means that bar will have a prototype of Foo and also will have an own property (i.e. not in the prototype) of buz.
Now, the prototype of bar, which points to Foo, can be found (at least in Chrome, since this is implementation specific) on the property __proto__. So this is true: bar.__proto__ === com.foobar.Foo.
Moving forward, if you want bar to also be a superclass prototype of another object, you'd do the same:
var subbar = Object.create(bar);
Makes sense? I'll later add more about Function, the property prototype and the new operator if you want....
You are not able to instantiate Foo because it is an object, not a function. You can accomplish that by creating a function and using prototype to set the instance methods:
// constructor method
com.foobar.Foo = function() {
this.foo = 'foo'
this.bar = 'bar'
}
com.foobar.Foo.prototype.baz = function() {
return true
}
Take a look at it running on jsfiddle: http://jsfiddle.net/DE7KZ/
All, I found there are 3 ways to declare object in javascript.
var Waffle = {
tastes:'yummy'
};
var Waffle = function()
{
this.tastes='yummy';
};
function Waffle() {
var that = {};
that.tastes = "yummy";
return that;
}
The first way is Object literal it doesn't have a constructor.
I think the equal way to Object literal is below.
var Waffle = new Object();
Waffle.tastes = 'yummy';
(If my understanding is wrong. Please correct me.)
I want to know what the difference of these 3 ways is.
Which one is the best choice?
Thanks.
The literal notation and new Object() creates an object whose prototype is directly the Object. Also, properties and methods are attached on the instance.
/*
Object
A
| instance.__proto__
|
instance
*/
//all 3 yield the same result
var foo1 = {
bar : 'bam!'
}
var foo2 = {}
foo2.bar = 'bam!';
var foo3 = new Object();
foo3.bar = 'bam!';
The constructor approach, either the declared function or the assigned function expression approach, has an additional prototype level between the instance and the Object, which contains your prototype functions attached to the constructor's prototype. Anything attached to the constructor's prototype are shared across all instances.
/*
Object
A
| instance.__proto__.__proto__
|
constructor.prototype
A
| instance.__proto__
|
instance
*/
//these 2 are the same
//bar is attached at the instance
//function expression assigned to variable foo1
var foo1 = function(){
this.bar = 'bam!'
}
//function declaration named foo2
function foo2(){
this.bar = 'bam!'
}
//==========================================================================//
//these 2 are the same, but not the same as above
//methods live on the prototype level and are shared across instances
//function expression assigned to variable foo1
var foo1 = function(){}
//function declaration named foo2
function foo2(){}
foo1.prototype.bar = 'bam!'
foo2.prototype.bar = 'bam!'
The third approach returns a new literal. You don't get the benefits of the constructor method and prototype sharing. It's as if you just called Waffle like an ordinary function, created a literal, attached properties and methods, and returned it.
Best Choice: Depends on purpose.
Object literals:
Shorter than new Object and can attach methods/properties upon definition.
Properties/methods live on the instance, no running up the prototype chain which means faster look-up.
Unoptimized creation of objects might lead to duplicates, which waste memory. For example, creating functions per instance instead of sharing via the prototype.
Constructor:
Classical OOP style
Inheritance
Shared methods via the prototype means less memory used, as opposed to per instance methods.
Forgetting the new might have unwanted consequences, like attaching globals (if window is the context)
You can check these out in the Chrome Developer tools. Create them in the Console, and watch these expressions in the Sources tab
The first is an object literal and is the same as:
var Waffle = new Object();
Waffle.tastes = 'yummy';
which is the same as:
var Waffle = {};
Waffle.tastes = 'yummy';
but of course, their instantiations take multiple lines.
Your second and third examples are functions. Your second example is an expression, while your third example is a declaration. Here's an explanation of their differences: What is the difference between a function expression vs declaration in JavaScript?
Be careful with your second example (the expression), because in order to modify this (correctly), you need to use var waffle = new Waffle();. Since this is an expression, alternatively you could've used a declaration like:
function Waffle() {
this.tastes='yummy';
}
(to understand the main difference between that and the original, which I don't think affect many people ever, read the link I provided)
The third example is a basic function that returns a new object literal.
As for the best choice...I don't think there's a concrete, definite answer.
Your first example creates a simple, single object. You can add/change properties and methods on it. But it inherits directly from Object. I like to use this when I need one big object for holding many things, and its structure is static. To reuse this, your third example is needed.
Your second example is convenient because you can invoke a new instance, giving the effect of classic OOP...and is the one I normally use. Although the caveat is that you have to use new, otherwise the value of this will be window, which is bad. At the same time, you can modify this prototype and all instances will share it. It also gives you flexibility of having "private" variables, such as:
function Waffle() {
var testing = 0;
this.name = "A";
this.myMethod = function () {
return testing;
};
}
Your third example is similar to the second, except that you can't tap into a prototype, since you're returning an Object. It's basically using your first example, but making it reusable. It also allows for "private" variables like above, as well.
So if you're looking for a single object, use your first example. If you're looking for reusability, I'd suggest your second example, while the third is still an example. Hopefully I explained enough about each for you to determine which suits your needs.
All, I found there are 3 ways to declare object in javascript.
var Waffle = {
tastes:'yummy'
};
var Waffle = function()
{
this.tastes='yummy';
};
function Waffle() {
var that = {};
that.tastes = "yummy";
return that;
}
The first way is Object literal it doesn't have a constructor.
I think the equal way to Object literal is below.
var Waffle = new Object();
Waffle.tastes = 'yummy';
(If my understanding is wrong. Please correct me.)
I want to know what the difference of these 3 ways is.
Which one is the best choice?
Thanks.
The literal notation and new Object() creates an object whose prototype is directly the Object. Also, properties and methods are attached on the instance.
/*
Object
A
| instance.__proto__
|
instance
*/
//all 3 yield the same result
var foo1 = {
bar : 'bam!'
}
var foo2 = {}
foo2.bar = 'bam!';
var foo3 = new Object();
foo3.bar = 'bam!';
The constructor approach, either the declared function or the assigned function expression approach, has an additional prototype level between the instance and the Object, which contains your prototype functions attached to the constructor's prototype. Anything attached to the constructor's prototype are shared across all instances.
/*
Object
A
| instance.__proto__.__proto__
|
constructor.prototype
A
| instance.__proto__
|
instance
*/
//these 2 are the same
//bar is attached at the instance
//function expression assigned to variable foo1
var foo1 = function(){
this.bar = 'bam!'
}
//function declaration named foo2
function foo2(){
this.bar = 'bam!'
}
//==========================================================================//
//these 2 are the same, but not the same as above
//methods live on the prototype level and are shared across instances
//function expression assigned to variable foo1
var foo1 = function(){}
//function declaration named foo2
function foo2(){}
foo1.prototype.bar = 'bam!'
foo2.prototype.bar = 'bam!'
The third approach returns a new literal. You don't get the benefits of the constructor method and prototype sharing. It's as if you just called Waffle like an ordinary function, created a literal, attached properties and methods, and returned it.
Best Choice: Depends on purpose.
Object literals:
Shorter than new Object and can attach methods/properties upon definition.
Properties/methods live on the instance, no running up the prototype chain which means faster look-up.
Unoptimized creation of objects might lead to duplicates, which waste memory. For example, creating functions per instance instead of sharing via the prototype.
Constructor:
Classical OOP style
Inheritance
Shared methods via the prototype means less memory used, as opposed to per instance methods.
Forgetting the new might have unwanted consequences, like attaching globals (if window is the context)
You can check these out in the Chrome Developer tools. Create them in the Console, and watch these expressions in the Sources tab
The first is an object literal and is the same as:
var Waffle = new Object();
Waffle.tastes = 'yummy';
which is the same as:
var Waffle = {};
Waffle.tastes = 'yummy';
but of course, their instantiations take multiple lines.
Your second and third examples are functions. Your second example is an expression, while your third example is a declaration. Here's an explanation of their differences: What is the difference between a function expression vs declaration in JavaScript?
Be careful with your second example (the expression), because in order to modify this (correctly), you need to use var waffle = new Waffle();. Since this is an expression, alternatively you could've used a declaration like:
function Waffle() {
this.tastes='yummy';
}
(to understand the main difference between that and the original, which I don't think affect many people ever, read the link I provided)
The third example is a basic function that returns a new object literal.
As for the best choice...I don't think there's a concrete, definite answer.
Your first example creates a simple, single object. You can add/change properties and methods on it. But it inherits directly from Object. I like to use this when I need one big object for holding many things, and its structure is static. To reuse this, your third example is needed.
Your second example is convenient because you can invoke a new instance, giving the effect of classic OOP...and is the one I normally use. Although the caveat is that you have to use new, otherwise the value of this will be window, which is bad. At the same time, you can modify this prototype and all instances will share it. It also gives you flexibility of having "private" variables, such as:
function Waffle() {
var testing = 0;
this.name = "A";
this.myMethod = function () {
return testing;
};
}
Your third example is similar to the second, except that you can't tap into a prototype, since you're returning an Object. It's basically using your first example, but making it reusable. It also allows for "private" variables like above, as well.
So if you're looking for a single object, use your first example. If you're looking for reusability, I'd suggest your second example, while the third is still an example. Hopefully I explained enough about each for you to determine which suits your needs.
I found the following code somewhere, but I am not understanding the code properly.
ArticleVote.submitVote('no');return false;
Is ArticleVote a class and submitVote() a function of that class?
Or what does the above code mean? And is there any concept of classes and objects in jQuery or in traditional JavaScript? How to create them? Please share some reference links or code.
Everything is an object in JavaScript
As opposed to other purportedly pure OOP languages. Functions are objects too, but they may just as well be constructor of objects.
var ObjectCreator = function () {
};
The above is a function which if called appropriately, creates an object. Called appropriately means that you have to use the new operator:
var obj = new ObjectCreator;
So while JavaScript does not have classes per se, has means to emulate that behavior. For example:
class Foo {
public void bar() {}
}
Foo foo = new Foo();
is equivalent to the following JS code:
var Foo = function () {
// constructor
};
Foo.prototype.bar = function () {}
var foo = new Foo;
Inheritance is different
The real difference comes when you want to use inheritance, which is a different type of inheritance (prototypal). So, given two pseudo-classes Foo and Bar, if we want Bar to extend from Foo, we would have to write:
var Foo = function () {};
var Bar = function () {};
Bar.prototype = new Foo; // this is the inheritance phase
var bar = new Bar;
alert(bar instanceof Foo);
Object literals
While constructor functions are useful, there are times when we only need only one instance of that object. Writing a constructor function and then populate its prototype with properties and methods is somehow tedious. So JavaScript has object literals, which are some kind of hash tables, only that they're self-conscious. By self-conscious I mean that they know about the this keyword. Object literals are a great way to implement the Singleton pattern.
var john = {
age : 24,
isAdult : function () {
return this.age > 17;
}
};
The above, using a constructor function would be equivalent to the following:
var Person = function (age) {
this.age = age;
};
Person.prototype.isAdult = function () {
return this.age > 17;
};
var john = new Person(24);
What about that prototype thingy
As many have said, in JavaScript objects inherit from objects. This thing has useful aspects, one of which may be called, parasitic inheritance (if I remember correctly the context in which Douglas Crockford mentioned this). Anyway, this prototype concept is associated with the concept of prototype chain which is similar to the parent -> child chain in classical OO languages. So, the inheritance stuff. If a bar method is called on a foo object, but that object does not have a bar method, a member lookup phase is started:
var Baz = function () {};
Baz.prototype.bar = function () {
alert(1);
};
var Foo = function () {};
Foo.prototype = new Baz;
var foo = new Foo;
/*
* Does foo.bar exist?
* - yes. Then execute it
* - no
* Does the prototype object of the constructor function have a bar
* property?
* - yes. Then execute it
* - no
* Is there a constructor function for the prototype object of
* the initial construct function? (in our case this is Baz)
* - yes. Then it must have a prototype. Lookup a bar
* member in that prototype object.
* - no. OK, we're giving up. Throw an error.
*/
foo.bar();
Hold on, you said something about parasitic inheritance
There is a key difference between classical OO inheritance and prototype-based inheritance. When objects inherit from objects, they also inherit state. Take this example:
var Person = function (smart) {
this.smart = smart;
};
var Adult = function (age) {
this.age = age;
};
Adult.prototype = new Person(true);
var john = new Adult(24);
alert(john.smart);
We could say that john is a parasite of an anonymous Person, because it merciless sucks the person intelligence. Also, given the above definition, all future adults will be smart, which unfortunately is not always true. But that doesn't mean object inheritance is a bad thing. Is just a tool, like anything else. We must use it as we see fit.
In classical OO inheritance we can't do the above. We could emulate it using static fields though. But that would make all instances of that class having the same value for that field.
Javascript supports objects but not classes - it uses a prototype-based object system.
JavaScript supports object-oriented development
Object-oriented JavaScript
Certainly JS has objects and classes, but it's not exactly a conventional approach.
It's rather a broad question, but there's three main things you want to know about objects and classes in JS:
1). Everything is an object - this famously includes JS's first class functions
2). There are object literals
var myObject = { "foo": 123, "bar": [4,5,6] };
3). Inheritance is prototype based, so creating classes is more a matter of form than function. To get the effect of a class you'd write something like:
function myClass(foo)
{
this.foo = foo;
}
myClass.prototype.myFooMethod = function() {alert(this.foo);}
var myInstance = new myClass(123);
myinstance.myFooMethod(); // alerts 123
For your example it's likely that ArticleVote is an object instance and probably not conceptually a class, and submitVote would be a method of the object. can't tell for sure though, it could be what you'd call a static method in another language.
Yes, JavaScript has impressive support for Object Oriented programming, Objects and functions. In fact, I'm surprised that you have to ask this question! There are a wealth of resources online such as:
http://mckoss.com/jscript/object.htm
http://www.webreference.com/js/column79/
http://www.javascriptkit.com/javatutors/oopjs.shtml
More resources:
http://www.google.com/search?q=object+oriented+programming+javascript
JavaScript frameworks such as jQuery and Prototype could not have been built without this support in JavaScript engines.
You can achieve the above through Javascript, nothing to do with jQuery.
var ArticleVote= {};
ArticleVote.submitVote = function(voteResult) {
console.log(voteResult);
}
function Vote(){
ArticleVote.submitVote('no');
return false;
}
You can use the JavaScript function as class.
ClassUtil = function(param){
privateFunction = function(param){
// Do some thing
return valueParam;
}
this.publicFunction = function(){
var val1 = function1();
if (val1){
return true;
} else{
return false;
}
}
}
function getClass(){
var classUtil = new ClassUtil();
alert(classUtil.publicFunction());
}
There is one public and one private function. You can call public function from out side using object of the class.