Google Closure Library inherits properties - javascript

I'm experimenting with the Google closure library and in particluar its 'inherits' method.
I have one question. When I extend a base class, if I do not set the base class's properties in its constructor, all the children end up sharing the properties, for example, if I add items to an array the array just keeps getting bigger.
Could someone explain why I need to set the properties in the constructor?
Here's my example, if you comment out "this.list = [9,8,7];" in the 'Person' constructor, the children share the persons list and keep adding to it.
http://jsbin.com/imujoy/1/edit
Thanks for any help.

When you reference "this.list" from the child, it first looks at the object itself to find that property. When it cannot find it, it looks at its prototype and finds the "list" array. That list, however, is a reference to the same list you created on the prototype of the Person. If you assign a new "this.list" in the constructor, you are just assigning a property on the object rather than the prototype. Generally speaking, you should not assign non-primitive types (Arrays, Objects) on the prototype if you intend to use an inheritance model because the children will share the same reference.

Are you copying parent defined variables in the child using Parent.call(this) or Parent.apply
function Child(){
Parent.apply(this,arguments);
}
goog.inherits(Child, Parent);
list becomes a property of any Child instance when defined in the Parent in the following manner:
function Parent(){
this.list=[];
}
Basic prototype behavior:
Prototypical inheritance - writing up
Good reference dealing with constructor parameters but to apply you have to implement _init and change goog.base:
How to "properly" create a custom object in JavaScript?

Related

JavaScript - Confusion between global classes and inheritance

Total begginer who learns JS here. I don't understand why when you declare a variable it doesn't TOTALLY inherit of it's parent class methods, for e.g.:
// I initiate an array (my question is the same for all type of vars)
var myArr = ["foo", "bar"]
// Let's say I call a random function of the parent class Array
console.log(Array.isArray(myArr)); // true
// Since I assume that myArr inherited of the COMPLETE LIST of Array's methods, I should be able to do this:
console.log(myArr.isArray()); // Uncaught TypeError
Why don't the variables inherit of all of the methods of it's parent classes? Instead of that you need to mix between the fonctions of Array and myArr. They should be identitical on the two sides, no?
Array.isArray can also be called on non-arrays, so calling it from the instance of other classes would not have the method, resulting in a runtime error. Basically if you knew it was an array and it would be callable, you would not need to call it.
That is why it is NOT on the Array prototype and NOT callable from the instance.
const a = null
a.isArray() // bad
Array.isArray(a) // good
Developers have the option in Javascript to add methods to the class, the instance (aka prototype), or both. In this case it was only added to the class, not the instance.
It could have been added to the prototype of Object, but then it still would not be on the instances of boolean, number, string, symbol, or undefined.
When you declare a variable it is an instance of a Class, there is not inheritance.
When you declare a class that extends another class is where inheritance occurs.
Array.isArray() is a static property of the JavaScript Array object.
Usually, static methods are used to implement functions that belong to the class, but not to any particular object of it.
You need to pass an array as a parameter to the isArray function.Eg:
console.log(myArr.isArray(myArr))

how working to Object.prototype in JavaScript

I am saw the documentation of JavaScript and I am readed about :
Object.prototype and in the documentation they comment that:
The Object.prototype property represents the Object prototype object.
ok I understand tha I can create an Object of this way:
var o = new Object();
but what meaning this:
** property represents the Object prototype object**
ok I know what is Object:
The Object constructor creates an object wrapper.
my question is :
what do you mean when you say this:
The Object.prototype property represents the Object prototype object.
also while researching I saw this about prototype, this protoype term is the same to this Object.prototype?:
object that provides shared properties for other objects
here I saw that
I hope my question is bad just I am not understand this term?
Javascript uses creational Prototype pattern. To make this simple, every time you call new Object(), or Object.create you are technically cloning prototype object. Object.prototype just holds reference to the prototype object.
Now why is this important? Because whatever you put on your prototype will be cloned. There is difference if you put functions on prototype, which your created/cloned objects just hold reference to, so when you change the function on prototype, it will reflect on all created object. If you specify variables though, their values will be cloned and so each object you create will have it's own values.
Objects in Javascript can inherit each other. That means if we got an object child that inherits a parent object, you can access all the properties of the parent through the child:
const parent = { age: 37 };
const child = Object.create(parent); // child inherits parent
console.log(child.age); // 37
Now parent is called the prototype of child. Now the Object.prototype property is the upmost parent in the inheritance chain, in our case it is:
child -> parent -> Object.prototype
So every object (and nearly everything else) inherits from that property. That means that if you add something to it:
Object.prototype.test = "hey!";
All the children (everything) inherits it:
console.log({}.test, 1..test, "test".test); // hey, hey, hey!

Javascript - Object.create: Is my understanding correct?

I am trying to understand fully how prototypes work.
This is my definition of a prototype:
A built in property that all objects have (except the Base Object) which points to and references a 'proto{}' object which is a copy of another object whose properties and methods can then be referenced if not found in the original object.
Is that correct? Especially I'm wondering about the 'is a copy of another object' part - meaning that the JS Engine creates a stored copy of Object B in memory space which the prototype property of Object A points to for reference.
Now my questions about Object.create:
My understanding is that this method makes the prototype (or the object itself?) of whatever object it is used on, inherit (IOW, reference a copy of the passed in Object) the properties and methods of another object that is passed in.
var john = Object.create(Person);
In the above code, the john object is created and it's
prototype property points to a created object that has the methods and
properties of the Person object? Or to put it differently, Object.create makes a copy of the Person object and puts it in a memory space that the prototype property of john points to. Is this a correct understanding of what's going on?
If so, is the reason that a copy of the object ('person') is made, that the prototype of john points to, because that allows the values of the properties and methods to be modified without overwriting the props/methods in the Person object that the prototype object associated with john inherited?
I am trying to break this down so I can understand and trying not to over-complicate the concept.
Here is a picture I drew to further illustrate my current understanding:
No, there is no copying of anything involved. Just strike that part:
Prototype: A built in property that all objects have (except the Base Object) which points to and references a 'proto{}' object which is a copy of another object whose properties and methods can then be referenced if not found in the original object.
Keep it simple.
And yes, because there is a direct reference and nothing else involved, this means that any changes to the inherited properties of the prototype object will dynamically reflect in the object.

Is there any relationship between a functions code body and it's prototype?

I have been going through Javascript Koans when I hit upon the part about inheritance. I became deeply fascinated and spent the entire morning researching how inheritance works in JS.
I understand that a function can be used to execute code which is declared in its code body, and a function can also serve the purpose as a constructor for objects which inherent from that functions prototype object.
It seems as though functions have two purposes that are not at all related- the ability to create objects, and the ability to execute it's declared code. Is there any relationship between these two abilities?
An attempt at a simple answer (with some approximations to try and keep it simple)
You could see a "class" function both as the constructor of the underlying object and the place where its methods are defined.
Construction
The new operator will create an empty object whose type will reference the function and bind it to this, then call the function.
The function may set some properties of this, which will become values for the new instance properties.
Methods
In JavaScript almost everything, notably functions, can have properties.
Among these, the conventionally named prototype property is the container of all class methods (and possibly other property values).
function Guy (name) { this.name = name; }
Guy.prototype = {
sayHello: function () { console.log ("Hello, I'm "+this.name; }
}
the Guy method sayHello is literally the property Guy.prototype.sayHello, which happens to be a function.
You could just as well add values instead of functions to the prototype property, which would act as class variables (of sorts).
So let's create an object Bob from the function/class Guy:
var Bob = new Guy("Bob");
Bob.sayHello();
when you invoke Bob.sayHello(), the virtual machine will first look for a Bob.sayHello property (which usually does not exist), then for a Guy.prototype.sayHello (and would go up the inheritance chain or die trying, but that's another subject), then bind this to Bob and call Guy.prototype.sayHello, which will be able to access the Bob instance through this.
As an illustration of the mechanism, you can break the prototype chain for a given object instance:
Bob.sayHello = function () { console.log ("my real name is Robert"); }
The duality you're describing doesn't in fact exist. Functions exist to be executed. But, in JavaScript, functions are also objects, so they can have properties such as prototype. (You can add other properties to your function and use them from its body as a means of making it "stateful".) From the function's point of view, prototype is just another ordinary property.
Object construction is the domain of the new operator. What it does, is this:
it creates an empty object,
it creates a hidden, non-modifiable binding between the created object and its constructor, which is then used to look-up a property value on its prototype whenever a property doesn't exist on the object itself,
it executes the provided function in context of that object (this points to it during that function's execution), and
it returns either the created object (if the provided function returned undefined) or the return value of the provided function.
(The {} notation for creating objects is just a shortcut for new Object().)
Additional note on prototypal inheritance (that is used in JavaScript): The second step in the above sequence has an important result. Any object in JavaScript has a constructor ({} has Object as constructor), so setting an object as the value of prototype property of your function doesn't just create a single binding. It transitively creates a "prototype chain". Any property is then looked up first on the object, then on its constructor's prototype, then on it's constructor's prototype's constructor's prototype, etc.

What is Prototype COMPOSITION or INHERITANCE?

Is the purpose of prototype to create methods and properties globally?
So that means all the instance can access it?
The said methods and properties are not inside the constructor, is that means they are not created every time an object is created?
Is prototype an object inside TheClass?
TheClass.prototype.someProperty = "hello";
So in the statement above, is that creating property inside the prototype object?
If so then how can a class access that property if it is created inside the prototype object?
these is how to access the property
var obj = new TheClass();
alert(obj.someProperty);
not this
alert(obj.prototype.someProperty);
also toString() is inside the prototype object
you called the toString() by calling the object the toString belongs, but toString() belongs to prototype object right?
How come it is called by calling the object not the prototype who is inside an object.
im familiar with java this is called COMPOSITION.
so why this work? I understand if its INHERITANCE but no it is COMPOSITION and we didnt write a statement delegating the toString() method of prototype to the object.
alert(theClass);
not
alert(prototype);
Classes which inherit from a particular class have access to the methods on that class's prototype. That makes prototype an inheritance-based construct.
Is the purpose of prototype to create methods and properties globally?
Yes. Prototype allows you to give instances of a class methods and properties which can be inherited from that class.
So that means all the instance can access it?
Yep.
Is prototype an object inside TheClass?
No. Prototype is a set of properties which classes inheriting from TheClass are granted access to as well. If a property isn't found on a particular object it will search the prototype chain for that property.
Properties in JS are looked up using the prototype chain
https://developer.mozilla.org/en/JavaScript/Guide/Inheritance_constructor_prototype
Is the purpose of prototype to create methods and properties globally?
Yes, you add properties and methods to the prototype such that all instances of the function have access to the same methods and properties. Any changes to methods/properties in a function's prototype affect all instances of that function
So that means all the instance can access it?
Yes.
The said methods and properties are not inside the constructor, is
that means they are not created every time an object is created?
Yes, they aren't re-created on every initializaiton - that is one of the main purposes.

Categories