Setting function prototype to a new object - javascript

I've been seeing this pattern in code recently:
function Person(){
this.name = "Dan";
}
Person.prototype = {
whatAmI: function(){
alert("I am a person")
}
}
On the above object person object, you can only reference the function whatAmI by calling Person.prototype.whatAmI() instead of Person.whatAmI() .
Is there any particular reason that this is done? Tt seems like its becoming popular and I cant see the benifit other than having methonds hidden on the prototype object instead of the Person object.
I understand the basics prototypes in Javascript, and I understand that using Person.prototype.whatAmI is a little unconventional in code instaed of just calling new Person(). However, I'm talking about places where the Person object is returned from another function call, and used as a normal object. Thus, the only way to call whatAmI is via Person.prototype.whatAmI

The purpose of the prototype property on functions is that it determines what prototype is assigned to objects created via the new expression when it's used with that function, e.g.:
var p = new Person();
Now, p's underlying prototype is the object that Person.prototype referred to when the new expression was evaluated, so:
p.whoAmI();
works.
In general, replacing the object on the prototype property isn't a great idea and you should only do it when setting up inheritance hierarchies. Instead, just add to the existing object:
function Person(){
this.name = "Dan";
}
Person.prototype.whoAmI = function(){
alert("I am a person")
};
A bit tangential, but:
You do have to replace the object, though, when setting up hierarchies.
// Base
function Person(name) {
this.name = name;
}
Person.prototype.whoAmI = function() {
alert("I am " + this.name);
};
// Derived
function Employee(name, position) {
Person.call(this, name);
this.position = position;
}
Employee.prototype = Object.create(Person.prototype);
Employee.prototype.constructor = Employee;
// Augmenting the derived prototype
Employee.prototype.whatDoIDo = function() {
alert("I hold the position " + this.position);
};
(That's not meant to be the be-all, end-all of hierarchies, just a quick example.)

whatmI is meant to be called on Person instances, e.g.:
var bob = new Person();
bob.whatAmI();
The prototype property of a constructor has properties that are accessible to all constructed instances of that constructor.
The ECMAScript 5 specification has a pleasantly readable explanation of the language's prototype-based inheritance:
Each constructor is a function that has a property named “prototype” that is used to implement prototype-based inheritance and shared properties. Objects are created by using constructors in new expressions; for example, new Date(2009,11) creates a new Date object...
Every object created by a constructor has an implicit reference (called the object’s prototype) to the value of its constructor’s “prototype” property. Furthermore, a prototype may have a non-null implicit reference to its prototype, and so on; this is called the prototype chain. When a reference is made to a property in an object, that reference is to the property of that name in the first object in the prototype chain that contains a property of that name. In other words, first the object mentioned directly is examined for such a property; if that object contains the named property, that is the property to which the reference refers; if that object does not contain the named property, the prototype for that object is examined next; and so on.

Prototype is actually a built in way in JavaScript for accomplishing inheritance. An object that has already been defined can have methods and properties added to it by accessing it's prototype.
Go right to the authority on the subject and read up. This topic in particular is what makes JavaScript cool.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain

There is no specific reason. It depends on what you want.
If the whatAmI function is needed on instances of the type Person, then you define it on the protoype. If you want it on the type, you can do,
Person.whatAmI = function(){
alert("I am a person")
}
They are both valid uses of the language. What you do depends on your application.

Related

The prototype property and inheritance in JavaScript

The prototype property and inheritance in JavaScript is not clear to me.
I have a function:
function User (name) {
this.name = name;
}
Questions:
1) Why one of the following is false and the other is true?
User.prototype.hasOwnProperty('name'); // false
User.hasOwnProperty('name'); // true
2) What is de difference between the followings:
User.constructor;
User.prototype.constructor;
3) What happens with the User.constructor and User.prototype.constructor if I override the prototype property like this:
User.prototype = {
changeName: function(newName) {
this.name = newName;
}
};
And what if I override it like this:
User.prototype = {
constructor: User,
changeName: function(newName) {
this.name = newName;
}
};
4) Is User a function or a prototype or what? The following site refers it as prototype: 'The following example creates a prototype ...'
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor
Thank you very much for your answers.
First you need to understand what a prototype is.
In Javascript, almost everything is an object.
Edit (thanks #Mathletics):
Primitive booleans, numbers, and strings are not objects
When you create an object in Javascript, by default, its prototype will be an Object.
So, if I do:
var obj = {};
console.log(obj.__proto__)
This yields:
Object {}
Pause:
To understand the difference between obj.prototype and obj.__proto__, please, refer to this thread.
The next step is to understand the concept of prototype chaining.
This is how inheritance is structured in Javascript. Basically, a prototype is the "parent" of another object, from which it derives methods and properties.
Imagine a scheme where a Rabbit inherits from Mammal, which inherits from Animal. Representing this in Javascript prototype chain would be like:
(Rabbit) -> (Mammal) -> (Animal) -> (Object) -> null
With code:
function Animal(){}
function Mammal(){}
function Rabbit(){}
Mammal.prototype = new Animal();
Rabit.prototype = new Mammal();
If you are able to understand these concepts, you might find the answers to your questions yourself, but I'll try to make it clearer:
1) why one of the following is false and the other is true?
User.prototype.hasOwnProperty('name'); // false
User.hasOwnProperty('name'); // true
You should read the hasOwnProperty method reference:
Every object descended from Object inherits the hasOwnProperty method. This method can be used to determine whether an object has the specified property as a direct property of that object[...]
This is a way to assure that the property you are looking for is defined within the object itself, not deeper in the prototype chain.
A contrary example would be:
console.log(User.hasOwnProperty('constructor'));
Since the constructor property is defined deeper in the prototype chaing, it is not an "own property" of User object.
In your case, name is a property defined within your User object, but not defined in the context of the global Object.
2) what is de difference between the followings:
User.constructor;
User.prototype.constructor;
The fist like takes the constructor of User, the second takes the constructor of its prototype (in this case, the global Object).
3) what happens with the User.constructor and
User.prototype.constructor if I override the prototype property like
this:
User.prototype = {
changeName: function(newName) {
this.name = newName;
}
};
Please, read this thread.
TL;DR: when you assing directly to the prototype, you are breaking the prototype chain an creating a new one. In the Rabbit example, if you at some point did:
Rabbit.prototype = {
// ...
};
Your new prototype chain would be:
(Rabbit) -> (Object) -> null
So, in your first example, User.prototype.constructor would yield:
function Object{}
In your second example, it would yield:
function User(name)
Got it?
4) is User a function or a prototype or what?
User is an object whose prototype is a Function object, whose prototype is a Object object.
Drawing it:
(User) -> (Function) -> (Object) -> null
Hope I've been clear.
"Everything" in JS is an object.
So a function is a special type of object and that type of object has a property called name which is why User.hasOwnProperty("name") returns true. It has nothing to do with the property of the User object that same function can create. Try calling it something else and you will see this to be the case.
Any object derives from another object, namely it's prototype. The prototype of a function has a constructor property and __proto__ property but no name property.
So Ùser.prototype.hasOwnProperty("name")` should return false
Since all properties of the prototype are derived you can do this User.constructor even though User.hasOwnProperty("constructor") would return false
1) why one of the following is false and the other is true?
User.prototype.hasOwnProperty('name'); // false, A
User.hasOwnProperty('name'); // true, B
The prototype object hasn't been given a name property and it doesn't have one by default (as User is not native), so this is false for the prototype.
The Constructor User is a Function and you've defined the name of the function as "User". This is set on the function object when it's interpreted.
Are you sure you're not confusing this with (new User('foo')).hasOwnProperty('name'); // true?
This last case, the instance of User has a name property which is "foo", as set by the constructor User.
2) what is de difference between the followings:
User.constructor;
User.prototype.constructor;
User.constructor is Function because User is a function.
User.prototype.constructor is undefined, but you'd normally reference it back at User. This is what would later be accessed as (new User).constructor; // User
3) what happens with the User.constructor and User.prototype.constructor if I override the prototype [...]
Nothing happens to User.constructor in either case.
As for User.prototype.constructor, it wasn't define previously
so remains undefined in the first case
is set to User in the second case
Please note that in both of these cases the entire prototype is now pointing at a different Object so existing instances will not see these changes and the previous prototype chain is no longer accessible to new instances.
4) is User a function or a prototype or what?
User is a function and is a constructor. In JavaScript we call certain functions constructors if they will be used to build (construct) instances.
It may be helpful for you to see a more abstract example,
// A function `Foo` which will be our Constructor
function Foo(baz) {
this.bar = baz;
}
// notice here we have `Foo.name; // "Foo"`
// Setting up reference to the constructor through the prototype
Foo.prototype.constructor = Foo;
// Setting up reference to some other shared property through the prototype
Foo.prototype.fizz = ['buzz'];
And then usage
var foo = new Foo('hello world');
foo.bar; // "hello world" (own)
foo.fizz; // ["buzz"] (inherited)
foo.constructor; // Foo (inherited)
var bar = new Foo();
foo.fizz === bar.fizz; // true, this is the same Object reference - it is shared
Don't be afraid to try things out in your Console!
Javascript, unlike other languages (Java, ecc.), isn't class-based, it doesn't provide any way to define a class (actually, the next Javascript, ES6-Harmony, introduces the class keyword but it's just a syntactic sugar on top of prototype inheritance and, at the moment, isn't available in any browser)...
So, Javascript implements the (aka) OOP (Object Oriented Programming) via Prototype Inheritance.
If you want to create a custom object, you need to use a function that defines it. Example:
var Person = (function() {
/**
* this is the Constructor (if you have in mind a class-based language)
**/
function Person() {}
return Person;
})(window);
Doing that we have defined a New Object Person and we can have multiple instances of it using the new operator:
var me = new Person();
var you = new Person();
//...
As all languages do, javascript objects can have Methods and Properties, methods and properties can be both of Instance and Class.
var Person = (function() {
function Person() {}
/**
* Static Method
**/
Person.sayCiao = function() {};
/**
* Static Property
**/
Person.ciao = 'Ciao';
/**
* Instance Method
**/
Person.prototype.sayHello = function() {};
/**
* Instance Property
**/
Person.prototype.hello = 'Hello';
return Person;
})(window);
As you can see (try in your console), using the prototype property we can define methods or properties that all objects created by calling new Person inherit.
1) why one of the following is false and the other is true?
Of course, statics methods or properties don't belong to the instance and hasOwnProperty returns true only when is called using the constructor function. Viceversa, instances methods or properties belong only to their instances and hasOwnProperty returns true only when is called using the new operator. This is the normal behaviour that you can meet in other programming languages.
Note: in ES6 the Function Object has a property name and this is the reason how your test returns true, but isn't referenced to the name property that you define in the Person Constructor (read more).
Example of usage:
var Person = (function() {
function Person(name) {
this.firstname = name
}
Person.prototype.firstname = '';
Person.factory = function(name) {
return new Person(name);
};
return Person;
})(window);
var hitmands = Person.factory('Giuseppe');
console.log('you are', hitmands);
var you = Person.factory('BatMan');
console.log('hitmands is', you);
console.info('Person has a name?', Person.hasOwnProperty('firstname'));
console.info('You have a name?', you.hasOwnProperty('firstname'));
The property prototype belongs to the prototype chain, this is the reason how your test return false... ({}).hasOwnProperty('prototype')... You can read more following this link.
Simply prototype and what it contains doesn't is own property of your object.
2) what is de difference between the followings (ecc.)
As someone said, one belongs to the function and the other to the prototype property.
3) what happens with the User.constructor and User.prototype.constructor if I override the prototype property like this (ecc.)
You can use that way to extend behaviour from one class to another...
Read more about this.

understanding simple class emulator in JavaScript

Recently I started to learn a bit more advanced JavaScript (as far I only used jQuery for some simple tasks) and bought a book of Alex MaxCaw "JavaScript Web Applications". The first chapter treats about creating simple class emulator. I understand almost everything except for two lines of code marked with comments down below:
var Class = function(parent) {
var _class = function() {
this.init.apply(this, arguments);
};
if(parent) {
var subclass = function() {};
subclass.prototype = parent.prototype;
_class.prototype = new subclass();
};
_class.prototype.init = function() {};
_class.fn = _class.prototype;
//????
_class.fn.parent = _class;
//????
_class._super = _class.__proto__;
return _class;
};
Can anyone tell me what is purpose of these two lines? I'll be very thankfull.
Walking through the code:
Class is defined as a function that calls init with the arguments provided it. This means you can call it with standard constructor syntax using new eg. var instance = new Thingy() and get the init function called with the proper this value.
If you pass a parent class in, your class gets that class's prototype property added to the prototype chain of a new empty object which it uses as its prototype property. A more succinct way of doing this in modern browsers is _class.prototype = Object.create(parent.prototype);
The init function is defined. This should likely be overridden with more useful initialization code after a _class instance is created (or the code should be changed to allow the passing in of an init function when you create a Class... or allow the instance to walk the prototype chain to look for other init functions.
_class.fn is created to provide a reference to the _class constructor's prototype function.
_class.fn.parent is created to provide a reference back to the constructor. This may be useful if you are applying the prototype in some other context and want a reference back to the prototype's constructor.
_class._super is assigned the internal, non-standard __proto__ property of the constructor. Remember that constructors are functions and, in Javascript, functions are objects. This means they have their own internal prototypes. The earlier references to prototype are the prototype assigned to objects created with this constructor NOT the constructor's prototype itself. All functions inherit from Function.prototype, which is where they get bind, apply, etc. _super in this case is just a reference to Function.prototype.
As to when this type of _super is used, one could imagine doing the following:
function Maker(){ //this will be called as a constructor, ie. with new
var fun = function(){}; //Make a function
fun.__proto__ = this.__proto__; //yuck. Set the function's this value to the instance
return fun; //return the function
}
Maker.prototype={say:function(){console.log("Javascript is fun!.. And weird.")}};
var fun = new Maker();
fun.say() //"Javascript is fun!.. And weird."
console.log(fun.__proto__) // Object{say:function}
console.log(fun.bind) // undefined!!
Woah! What just happened?
In fact, you replaced your functions internal prototype with an Object. This allows you to build up interesting prototype chains and interact with both functions and objects in a similar way. Note, however, that the link with Function.prototype has been severed, which is why we don't have access to bind. However let's fix it with more prototype magic!
function FunctionConnector(obj){
for (var prop in obj){
if(obj.hasOwnProperty(prop){
this.prop=obj.prop
}
}
}
FunctionConnector.prototype=Function.prototype;
Maker.prototype=new FunctionConnector({say:function(){
console.log("Javascript is fun!.. And weird.")
}});
var fun = new Maker();
fun.say() //"Javascript is fun!.. And weird."
console.log(fun.__proto__) // Object{say:function}
console.log(fun.bind) // function bind(){ [native code] }
Now what is that FunctionConnector? It takes an object and, when called as a constructor, returns an object that both has all the properties of the passed object AND inherits from Function.prototype. As you can see, our access to bind has returned (Of course we also could have made do with our original implementation and just Function.prototype.bind.called our way to victory).
With this new pattern in hand it may be clearer what _super in your code does, namely it references the built in prototype of the _class constructor you are making (In our example the instance of FunctionConnector would be _super). This reference could be used to patch the prototype at runtime, call methods with apply or anything else you can due with a reference to an object.
This is, as you may have noticed a little hackish, especially since __proto__ is nonstandard. But it's also somewhat neat if you enjoy the patterns it allows. I'd recommend only doing something like this if you are very confident in your knowledge of Javascript inheritance, and perhaps not even then unless you are in charge of your entire code base.
From what i know, fn is just an alias to the prototype property
And about the _super, that one is for referencing to the "class" from which you are inheriting
Here's more about the use of _super and js inheritance: article

Purpose of this Javascript prototype snippet

Sorry I can't phrase this better. But I ran across some code like the following:
MyObject.prototype = Object.create(MyObject.prototype);
MyObject.prototype.constructor = MyObject;
And I just can't seem to figure out what it does. MyObject is defined above it something like this:
function MyObject(options) {
this.someProp = someDefault;
this.otherProp = process(options.something);
// etc...
}
and it's always called as a constructor. I'm just wondering what benefit those first two lines provide and if it's a known pattern in Javascript.
I just can't seem to figure out what it does
It creates a new object that inherits from [the old] MyObject.prototype via Object.create and then overwrites MyObject.prototype with that. It also explicitly adds a .constructor property which actually should be existing already.
I'm just wondering what benefit those first two lines provide
None, unless before that snippet someone has corrupted the prototype (like MyObject.prototype = Object.prototype) and this is an attempt to fix it.
…and if it's a known pattern in Javascript.
Not like this. Using Object.create to set up the prototype chain for inheritance between constructor-defined "classes" is a known pattern, but then the constructors would be different on each side of the assignment.
The two lines of code provided seem to be an incorrect attempt of the use of prototypal inheritance, but I see where you're going with this and what you're trying to accomplish.
As we know, there are two ways in JavaScript to define objects that have properties and methods as members - the object literal notation and function notation. Using object literal notation, we don't have immediate access to the new keyword (think of this like using abstract classes in Java or C#). With function notation, we have access to the new keyword because the initial declaration of an object as a function serves as our constructor.
In ECMAScript 5, The Object object was given a method called create that provided developers a simple way to create a new object from an existing object declared with the object literal notation. (See documentation here). However, objects created in function notation have problems with this method because they are Function objects. The Object.create method is a great way to use simple inheritance, allowing access to the base properties and methods.
With function notation, once the new keyword is used, the result is not a function, but rather an object. For example, I can test this:
var Obj = function(){};
console.log(typeof Obj) // "function"
console.log(typeof new Object()); // "object"
Because of this, you can only inherit once (meaning the child object cannot be derived from):
var MyObject = new Object();
var anotherObj = new MyObject() // throws exception
To alleviate this problem, you need to follow three steps:
Create your child object in function notation (so you can create new instances of it using the new keyword and inherit from it).
Set the child object's prototype (an object) to the result of a new instance of the base object (which will be an object as well).
Set the constructor of the child object (which happens to be on the object's prototype) back to reference the Function of itself (which is a function prior to instantiation). If you don't do this, the constructor will remain an object, which cannot spawn new instances.
From here, you can create new instances of both the child and parent objects and derive from both, using the pattern. Here's a practical example:
var Vehicle = function(){};
Vehicle.prototype.start = function() {
return this.make + " " + this.model + " " + "started";
}
var Car = function(color, make, model) {
this.color = color;
this.make = make;
this.model = model;
}
Car.prototype = new Vehicle();
Car.prototype.constructor = Car;
var myCar = new Car("red", "chevy", "aveo");
myCar.start(); //"chevy aveo started"
I really don't see any benefit in doing that.
What it's doing is providing the new object with the previous objects methods. But it's coming from the same object...
Here is a good example of JS inheritance:
http://jsfiddle.net/aDCmA/2/
var App = (function(){
var Being = function() {
this.living = true;
this.breathes = function () {
return true;
};
};
var Robert = function() {
this.blogs = true;
this.getsBored = function () {
return "You betcha";
}
};
Robert.prototype = new Being();
return {
Being: Being,
Robert: Robert,
being: function(){ return new Being(); },
robert: function(){ return new Robert(); }
}
}());
Here is another question that is similar: inherit prototype methods from other classes without overriding own prototype methods
Credit to Robert Nyman for originally blogging about it: http://robertnyman.com/2008/10/06/javascript-inheritance-how-and-why/
Let's see line by line:
MyObject.prototype = Object.create(MyObject.prototype);
This redefines MyObject.prototype to an object that inherits from MyObject.prototype. This is unusual, because it makes no sense to inherit from itself.
MyObject.prototype.constructor = MyObject;
Since the previous line overwrote MyObject.prototype, this is just fixing the constructor property that was lost in the process.
I can think of one scenario where tht might be useful: if some code before that messed up with MyObject.prototype, for example assigning the prototype of another constructor to it:
MyObject.prototype = SomethingElse.prototype; // wrong way to do inheritance.
Then the code you posted would be an attempt to fix it.
This is perfectly valid Javascript.
Any javascript function (say Func)can be used as a constructor and the constructor invocation also requires a prototype property (i.e. F.prototype or the prototype associated with the function) . Thus (almost) every function has a prototype property. The value of this property (i.e. Func.prototype).
Now the value of this prototype associated with the function is an object itself that has a single non enumerable property called constructor. And the value of this constructor property is the function object (i.e. F itself).
Lets take an example.
Say I construct a function Func
var Func = function() {
//your definition
};
Now since this can be invoked as a constructor it has to have a prototype property Func.prototype lets call this proto.
proto = Func.prototype;
Now the prototype has a single property (that is non enumerable) called constructor. This constructor has a value that is equal to the function object itself.
Dont believe me check it like this
Func.prototype.constructor === Func // =>true
Will always return true for any function.
Now from the code you explained :
So basically these two lines
MyObject.prototype = Object.create(MyObject.prototype);
MyObject.prototype.constructor = MyObject;
are modifying the value of the prototye to have a constructor property with the value of MyObject that is defined. But that would have happened anyways in the normal course of things. But the reason could be that maybe the prototype of the object has been changed earlier from the class it has been inherited from. In that case would those two lines make sense.
Hope that helps :)

In Javascript, why Object.getPrototypeOf(person) works but person.getPrototypeOf(person) won't?

For the following code, I wonder why Object.getPrototypeOf(person) works, but person.getPrototypeOf(person) won't work? I thought the rule is: if the object doesn't have such property or method, it will go up the prototype chain to try and get it, and call it on this (such as Animal.getName.call(this) where this is the context of the woofie object). So in that case, person.getPrototypeOf(person) should become Object.getPrototypeOf.call(person, person) and should work too?
function Person(name) {
this.name = name;
}
var person = new Person("Ang Lee")
console.log("the prototype of person is", Object.getPrototypeOf(person));
Update: for the answers that say getPrototypeOf is a static method, does that mean:
function Person(name) {
this.name = name;
this.foo = function() { ... }
}
Person.bar = function() { ... }
that foo is "in the chain", and callable by any inherited objects, while bar is not, and bar is like getPrototypeOf, which is a static method?
Object.getPrototypeOf is a property of the Object type itself, and not of the prototype of Object.
Because it's not actually in the prototype chain, it won't be found when you call person.getProtoTypeOf().
It's more akin to a "static method" as seen in other OO languages.
.getPrototypeOf is a function put on Object, not on it's prototype. You can look it up if you want:
"getPrototypeOf" in Object.prototype; // false
If getPrototypeOf were a method contained in Object.prototype, it would also be available on objects of type Person, however, getPrototypeOf is attached to Object, which is only the constructor function of Object instances, not the prototype.
For some reason, the creators of Javascript decided that prototypes are attached to constructor functions and not vice versa; if they hadn't made such questionable decision, you would not have had to ask this question.
P.S. anybody interested in a more elegant/clean implementation of prototype based object inheritance can check out http://iolanguage.com/

At what point is the prototype Object born in JavaScript?

Let's say I have a constructor function:
function Cat()
{
this.tail = "long";
this.colour = "black";
}
console.log(Cat.prototype);
// returns an empty [object Object] with no properties (checked with `for...in` loop).
So it seems at this point Cat.prototype doesn't havetail and colour.
var Charlie = new Cat();
console.log(Charlie.tail);
So how does Charlie inherit the properties of Cat if they are not defined in its prototype. I was under the assumption that the whole point of the prototype object is to mirror or store the properties of the constructor that will be inherited by all instances of cat- is this wrong?
At what point does the prototype Object get filled up with these properties? Or does this happen only when I explicitly set Cat.prototype.eyes = brown as an example?
Moreover, what is the correct approach for querying the properties of an Object's prototype? Is it a for...in loop? I guess it can't be Object.getOwnPropertyNames(Cat.prototype) because that would not return inherited properties.
You are defining the tail and colour properties directly on the instance. Those properties are not defined on the prototype object.
Btw, every function has a prototype property and it is created at the time when the function itself is created.
prototype is completely seperate from this.
All the things in this will not get inherited, the things in prototype will.
By default you inherit from Object.prototype (which is empty)
function Cat()
{
this.tail = "long";
this.colour = "black";
}
Cat.prototype.getColour = function () {
return this.colour;
}
WhiteCat.prototype = Cat.prototype;
WhiteCat.prototype.constructor = WhiteCat;
function WhiteCat(name){
Cat.call(this);
this.colour = "white";
}
var c = new Cat();
console.log(c.getColour()); // "black"
var w = new WhiteCat();
console.log(w.getColour()); // "white"
Prototypes in Javascript are a little different than what you are describing. In this case Charlie does have a tail because Charie IS A Cat that is, he is an instance of Cat the Cat class. In your Cat function you add the tail property to all cats with the this.tail = line. This happens entirely because you called the function Cat with the new keyword. When you do that, javascript creates a new object and then makes this point to that object in the context of the function.
Now prototypes work differently, they are best thought of as a chain that will be followed if a you go looking for a property or function that is not present in an object. For example, if try to go:
Charlie.tickle_wiskers();
Javascript will go looking for a function called tickle_wiskers in the charlie object. If it does not find that function it will look in Charlies prototype (which by default is Object.prototype if you don't set it explicitly). Finally I could give all Cats that function by going like this:
Cat.prototype.tickle_wiskers = function() {
alert('meow');
}
The prototype will never get the properties that you put in the object. The object has the members of the prototype, but the prototype doesn't have the members of the object.
The object doesn't inherit anything from the prototype, the members in the prototype still only exists in the prototype, they are only accessible from the object. If you remove something from the protype after an object is created, that member is no longer accessible from the object either.
A function has a prototype property, and when you use the new keyword to call the function as a constructor, the object that is created gets the prototype from the function.
If you add something to the prototype of a function, it will also be accessible by objects that were created using the function, even if you created them before adding it to the prototype:
function Cat() {}
var c = new Cat();
Cat.prototype.test = function() {
alert('test');
};
c.test(); // alerts 'test'
Moreover, what is the correct approach for querying the properties of an Object's prototype?
var myProto = Object.getPrototypeOf(someObject);
var names = Object.getOwnPropertyNames(myProto);
names.forEach(function (name) {
value = myProto[name];
...
});
Or does this happen only when I explicitly set Cat.prototype.eyes = brown as an example?
Yes, properties on the [[Prototype]] of an object are only set when you set them manually.
But since every "instance" of a prototype has a live pointer to the prototype object, these changes will reflect after the object has been created.
store the properties of the constructor that will be inherited by all instances of cat- is this wrong?
We don't store properties of objects on the prototype. We store properties (mainly methods) that we want to share among all instances of a prototype/constructor.

Categories

Resources