Inheritance of variable doesn't work - javascript

If I use prototypical inheritance in Javascript, the methods are available in subclasses but the members from parent are shared. Why is this?
For e.g., I am extending 2 data structure classes from my store.
function Store() {
this._store = [];
this._index = -1;
}
Store.prototype.addData = function (val) {
this._index++;
this._store[this._index] = val;
};
Store.prototype.toString = function() {
return "Store: [" + this._store + "]";
};
// inherits from Store
function DS1() {
}
DS1.prototype = new Store();
DS1.prototype.constructor = DS1;
Now if I use 2 instances of DS1, they are using the same store data. Why is that?
var ds1 = new DS1();
ds1.addData(2);
console.log(ds1.toString()); // Prints 2
var ds2 = new DS1();
ds2.addData(3);
console.log(ds2.toString()); // Prints 3
console.log(ds1.toString()); // Prints 3 and NOT 2.

This is one reason why use of new is discouraged for use with prototype. The problem is that a new unique _data array is created only when your Store constructor runs. Your Store constructor only runs one time, ever, in DS1.prototype = new Store(); This means that allnew DS1() instances share the same _data array.
Here's an relevant example adapted from a different answer of mine. Suppose each Store has a pseudo-unique, random id property:
var Store = function() {
// each Store instance has a random id
this.id = Math.random();
}
Store.prototype.addData = function() { /* ... */ }
Then, you want DS1 to inherit from Store:
var DS1 = function() {
this.something = 5;
}
DS1.prototype = new Store(); // this is bad
var ds1 = new DS1();
console.log(ds1.id);
var ds2 = new DS1();
console.log(ds2.id); // same as ds1!
Bad news -- DS1 instances all share the same id now! DS1.prototype.id is set once, ever, on the line DS1.prototype = new Store();, and that's where all DS1 instances get their id from.
Instead, you want to run the Store constructor code each time you run the DS1 constructor code, instead of just once when your set up the DS1 prototype:
var DS1 = function() {
Store.call(this); // set parent constructor properties on `this` new DS1 obj
//...
}
// DS1 prototype inherits from Store prototype, not Store instance
DS1.prototype = Object.create(Store.prototype);

This is because in Javascript object are not copied by value but only by reference.Now, the prototypes of children (here ds1, ds2) and parents point to same object, when a child modifies the prototype, the parents get the changes and so do the siblings. Inheritance in javascript can be achieve by creating empty function F() setting its prototype to prototype of parent constructor as below.
function extend(Child, Parent) {
var F = function () {};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
Child.uber = Parent.prototype;
}
This way you can inherit by simply using extend(ds1, Store); Inheritance and prototype chain

Add Store.call(this) to your DS1 "class". After that you can start assigning values for your DS1 specific properties inside the constructor.

As it was said in comments, all childs uses the same object as a prototype. That is how prototypical inheritance works.
The prototype object in such kind of inheritance stands as a spare storage of methods and variables for child objects.
When you call/get a var from d1 or d2 it looks if they have addData. They haven't. Then js looks into __prototype. Hey, new Store is there! Does it have a addData? Yes! Calling it...
It's important, that new Store is called once, so a created object stands for all childs of your parent.

Related

Using Object.create() the correct way

Learning Javascript I am finding different ways for creating objects. Seems that the way forward is using Object.create()
It's pretty hard to find a solid answer on best practises for using Object.create() as even the specific Object.create() articles seem to do things slightly different.
What I want to do is create multiple objects with their own encapsulated data.
I like to use encapsulation and what seems to work for me is something like
function Foo() {
var message = "Hello";
return {
bar:bar
}
function bar(){
return message;
}
}
World = (function(){
var obj = Foo();
var tank = Object.create(obj);
return {
baz:baz
}
function baz(){
alert(tank.bar());
}
})();
Running World.baz() works as expected but I am still not sure if I am doing this right.
All answers will be appreciated, thanks.
Generally in javascript you want to create objects like so:
var obj = {};
obj.someProperty = 'someValue';
obj.someOtherProperty = 'someOtherValue';
Or, you could use object literal notation, like this:
var obj = {
someProperty: 'someValue',
someOtherProperty: 'someOtherValue'
};
The Object.create function is an interesting one. Yes, it does create an empty object, but it isn't like the objects defined above. Instantiating and object with Object.create will give the new empty object inheritance up to the parameter you give the Object.create function. For instance, if we define an object as:
var actions = {
shout: function(message){
console.log(message.toUpperCase() + '!');
}
}
And then create a new object with Object.create():
var newObject = Object.create(actions); // creates a new object: newObject = {};
newObject will not contain any of it's own properties, but it will be able to access the properties of the parent actions object. After defining those object, try this out:
newObject.hasOwnProperty('shout'); // returns false
newObject.shout('Hello!'); // logs 'HELLO!!'
This example just goes to show how inheritance works from the newly created object to it's parent. This can be extremely useful, but make sure you specifically want that behavior before creating objects with Object.create-- otherwise, better be safe and use one of the two other methods above.
Hope that helps!
Edit:
Alternatively, if you're just trying to create many separate instances of the same object, you can create a constructor and invoke it with the new keyword, like this:
var Tank = function(speed, durability){
this.speed = speed;
this.durability = durability;
this.location = 0;
this.shoot = function(){
console.log('Pew pew');
};
this.move = function(){
this.location += speed;
};
}
var myTank = new Tank(5, 15); // creates new tank with speed 5 and durability 15,
// that also has all the default properties and methods,
// like location, shoot, and move.
var yourTank = new Tank(7, 12); // instantiates a different tank that myTank, with it's
// own speed and durability properties, but also has the
// default location, shoot, and move properties/ methods
var enemyTank = new Tank(10, 25);// instantiates yet another, unique tank with it's own
// unique values for speed and durability, but again with
// the default location, shoot, and move properties/methods
Try this approach for creating javaScript objects that encapsulating data. As you can see each instance of Foo has its own properties and state.
var Foo = function() {
var Foo = function Foo(customMessage) {
this.message = customMessage || "Hello";
}
Foo.prototype.message;
Foo.prototype.bar = function(){
return this.message;
}
return Foo;
}();
var tank1 = new Foo();
var tank2 = new Foo("Goodbye");
alert(tank1.bar());
alert(tank2.bar());
I would suggest using constructors to encapsulate data. If you really need to use Object.create(), you need to create a constructor-prototype system with Object.create(). However, in any case, you're just calling .bar() from the result of Foo() in the .baz() method of World. That does not mean World should point to the result of Foo().
Object.prototype.__construct = function() {
//This is the default constructor from any new object. We change it to change the constructor of objects as we go along. We could make no __construct method on Object.prototype because it doesn't do anything, so we're not going to call it, but we're going to define it anyway since we want all objects to have a __construct method, even if they don't define a new one on top of the default.
};
//Object.prototype is our default object. We add methods to object to change the prototype of objects as we go along.
var Foo = {}; //Any object that doesn't inherit from anything must inherit from Object.prototype. We do this by just setting it to {} (or new Object()).
//If we're going to define a new constructor, we need to call it _after_ we've defined it.
Foo.__construct = function() {
var message = "Hello!";
this.bar = function() {
return message;
}
};
Foo.__construct();
Foo.bar() //returns "Hello!"
//Note that message is encapsulated and _cannot_ be accessed through Foo itself.
var World = {}; //World _does not_ point to Foo. It simply calls a method of Foo in one of its methods.
World.__construct = function() {
//Now, if the method of Foo we're going to call in the method of World is going to alter Foo, then we should make a copy of Foo using Object.create(). The method we're going to call isn't _actually_ going to alter Foo, but it's good practice to make a copy because it _could_ if we made it so.
var obj = Object.create(Foo);
//Because Foo has been constructed and obj is a copy of Foo, we don't need to construct obj. We only need to construct an object if we define a new constructor property.
this.baz = function() {
alert(obj.bar());
};
};
World.__construct();
World.baz() //alerts "Hello!"
//Note that obj is encapsulated within World. obj points to Foo, but again, World _does not_ point to Foo.

defining method with prototype property and without prototype difference

please clarify the difference b/w this two codes
function Person(gender) {
this.gender = gender;
alert('Person instantiated');
}
Person.prototype.sayHello = function()
{
alert ('hello');
};
var person1 = new Person('Male');
var person2 = new Person('Female');
// call the Person sayHello method.
person1.sayHello()
and the second one is below where function define inside funciton (without prototype property)
function Animal(gender) {
this.gender = gender;
alert('animal instantiated');
this.sayToodle = function()
{
alert ('GOOOOOOO!!');
};
}
var Animal1 = new Animal('Male');
var Animal2 = new Animal('Female');
Animal1.sayToodle();
my more simple question are:
what is the difference?
define method inside or out side of a function. what is the effect?
if both same then which is the fine way to define this.
and what does prototype do?
Can we not define method of a obj out side of its function(CLASS)???
Defining a member inside the constructor (such as: this.name) gives only that instance of the object access to that member.
Defining a member inside the prototype allows all instances to "share" that property.
A way that helped me understand this was to define an array (or any other member that is not a method) inside the prototype, like so:
function Animal() {}
Animal.prototype = {
kids: [],
giveBirth: function() {
for(var i = 0; i < arguments.length; i++) {
this.kids.push(arguments[0]);
}
}
}
var cat = new Animal();
var giraffe = new Animal();
cat.giveBirth('kitten','another kitten','yet another kitten');
// cat.kids === ['kitten','another kitten','yet another kitten'];
// giraffe.kids === ['kitten','another kitten','yet another kitten'];
If you notice, the giraffe's kids were set (as kittens). Why is this? Because in this case, .giveBirth() accesses the prototype's kids array, which is shared by all instances.
What if we don't want to share the members, because the members are unique? You can do like so:
function Animal() {
this.kids = [];
}
Animal.prototype = {
giveBirth: function() {
for(var i = 0; i < arguments.length; i++) {
this.kids.push(arguments[0]);
}
}
}
var cat = new Animal();
var giraffe = new Animal();
cat.giveBirth('kitten');
// cat.kids === ['kitten']
// giraffe.kids == undefined
giraffe.giveBirth('baby giraffe');
// cat.kids === ['kitten']
// giraffe.kids === ['baby giraffe']
As you pointed out in the comments, part of how you decide to define the properties plays into memory usage; another part plays into what members you want to be "shared" across all instances.
To get a little more insight into prototypes (through understanding how new works), see What is the 'new' keyword in JavaScript?, on StackOverflow.
Here's a quote from there:
After a lot of searching, I have finally found out exactly what the
new keyword does, and it is 4 things:
It creates a new object. The type of this object, is simply object.
It sets this new object's internal, inaccessible, [[prototype]] property to be the constructor function's external, accessible,
prototype object.
It executes the constructor function, using the newly created object whenever this is mentioned.
It returns the newly created object, unless the constructor function returns a non-primitive value. In this case, that
non-primitive value will be returned.
Prototype members are shared among instances and members in the constructor function defined as this.something are instance specific.
When an instance need instance specific members (like Person.name) define it as this.name. When it can be shared (like a method sayName) define it on the prototype like: Person.prototype.sayName=function(){...
For more info on prototype and constructor functions you can check this answer.

Reason for using `prototype` instead of `this`

I am using Lightbox2
https://github.com/lokesh/lightbox2/blob/master/js/lightbox.js
And I don't understand why all the inner members of Lightbox are prototyped (Lightbox.prototype.init) and not simply members (Lightbox.init)?
If they are specific to each instance of lightbox wouldn't it be easier to use this.init?
Confused? Don't be...
Think of it this way:
Lightbox is your class definition, but it's not yet an instance.
Whatever you put directly on the class is like a static member:
Lightbox.staticFunc = function() {
// "this" will not point to instance object
};
Whatever you put on its prototype is a shared instance member:
Lightbox.prototype.instanceFunc = function() {
// "this" will point to object instance so members can be accessed
};
When you create an instance of a class, all instance members are accessible throught this keyword, but static ones through class definition:
var someData = Lightbox.staticFunc();
var l = new Lightbox();
l.instanceFunc();
Does this clear you understanding of prototype members?
Lightbox code then
The code that you've been looking at means this:
// this is a constructor that accesses instance properties (using "this")
// ------
// since properties are accessed via "this.something" means that they are
// not shared between instances but are part of one particular instance
// ------
function Lightbox(options) {
this.options = options;
this.album = [];
this.currentImageIndex = void 0;
this.init();
}
// adding an instance method that will be accessible to lightbox object instance
// that's why it can also access instance members (using "this")
// ------
// all functions that are defined on the prototype are shared between
// all instances so they consume less resources because not every
// object instance created them separately.
// ------
Lightbox.prototype.init = function() {
this.enable();
return this.build();
};
But some parts of this code are a bit confusing i.e.
LightboxOptions = (function() {
function LightboxOptions() {
this.fileLoadingImage = 'images/loading.gif';
this.fileCloseImage = 'images/close.png';
this.resizeDuration = 700;
this.fadeDuration = 500;
this.labelImage = "Image";
this.labelOf = "of";
}
return LightboxOptions;
})();
LightboxOptions class is contained within a function closure even though it doesn't define any private data, so the outer immediately executing function could be omitted in this example while having identical results:
LightboxOptions = function() {
this.fileLoadingImage = 'images/loading.gif';
this.fileCloseImage = 'images/close.png';
this.resizeDuration = 700;
this.fadeDuration = 500;
this.labelImage = "Image";
this.labelOf = "of";
};
It would of course be possible to define those functions in a constructor using this but then they wouldn't be shared between instances hence every object instance would define the same function hence consuming more resources. So this is not the same although from the execution point it does look the same:
CustomClass = function() {
this.prop = true;
};
CustomClass.prototype.method = function() { alert("I'm shared."); };
is slightly different than:
CustomClass = function() {
this.prop = true;
this.method = function() { alert("I'm duplicated in every instance."); };
};
The later consumes more resources while function is defined for every object instance.
...and a bit more to completely clear this thing
Suppose we have this class definition:
var C = function() {
this.prop = true;
this.method = function() { console.log("Per instance method"); };
}
C.prototype.method = function() { console.log("Shared instance method"); };
What happens here if we call these lines of code
var a = new C();
var b = new C();
a.method();
b.method();
delete a.method;
a.method();
b.method();
What do you think the output would be? You should get at least a little confused what happens after delete? Which method will get deleted? Per instance? Shared? Both? Well as it should be per instance method gets deleted on object instance a, that's why afterwards it reports that the shared method has been called. But only on a. b still has its own per instance method.
So without any further ado, output looks like this:
Per instance method // a.method
Per instance method // b.method
Shared instance method // a.method
Per instance method // b.method
What about prototype properties
These are different. When you create an object instance all those properties get copied to every object and are not shared. So whatever you do on them within the realm of a particular object will not get reflected to others.
If you'd then delete such property on a particular object it would still be available with its initial value as it was when object got instantiated.
var C = new function() {};
C.prototype.prop = 1;
var a = new C();
var b = new C();
a.prop = 10; // does not change the value of "b.prop"
delete a.prop; // "a.prop" is now back to 1
If they are specific to each instance of lightbox wouldn't it be
easier to use this.init?
They shouldn't be that's why they are putting everything in prototype object. When you use prototype, all methods still become available to you only that they do not become instance members.
JavaScript works with prototype chain, when it sees a method, it searches through the prototype chain till it finds the specified method. This process goes till the final Object object if not found in the middle.
You should only create instance members (via this) that you think are reasonable or needed because it adds an overhead (computational waste) if you put unnecessary methods using this keyword eg instance members.

use the JavaScript new keyword with variable length arguments array

I am building a function that allows an object to be extended by any other object
Object.prototype.extend = function(constructor, args) {
var proto = this;
while(proto.__proto__.constructor !== Object) {
proto = proto.__proto__
}
proto.__proto__ = new constructor(args)
console.log(this);
}
the method would be called like this:
function ChildModelConstructor(1,2,3) {
this.extend(ParentModel, arguments)
}
or
instanceOfChildModel.extend(ParentModel, [1,2,3])
the problem is if I call new like this:
new constructor(args)
the constructor of the parent object receives argument which is an arguments object or array.
What I would like is to be able to call
new constructor.apply(args)
or something similar, I am not trying to change the context of this new, apply is the only method of calling a method using an args object or an array that I am aware of.
Thanks for the help :)
Update, I found a better way
Here's a better approach to Inheritance I came up with, it avoids using the depreciated proto
There are several advantages to this method, over other inheritance schemes I've found. The biggest is that it does not merge multiple levels of the proto chain. Many schemes mix the childClass's proto methods with the parent classes instance variables, or worse, all methods and properties from the parents initialization directly into the main body of the childClass.
The drawbacks are, it is single inheritance, and you cannot change the inheritance of a single instance, since the prototype property belongs to the Constructor.
Function.prototype.inherit = function(parentClass) {
var newPrototype = Object.create(Object.create(parentClass.prototype));
for(key in this.prototype){
newPrototype[key] = this.prototype[key];
}
this.prototype = newPrototype;
this.prototype.constructor = this;
this.prototype.parentClass = parentClass;
this.prototype.initParent = function(args) {
var proto = Object.getPrototypeOf(Object.getPrototypeOf(this))
this.parentClass.apply(proto, args);
}
this.prototype.uber = function() {
return Object.getPrototypeOf(Object.getPrototypeOf(this));
}
}
and you can set up the inheritance like this:
function Model(n) {
this.initParent(arguments)
this.test = n*2;
}
Model.inherit(BaseClass);
Here is a slightly more detailed version in JSFiddle http://jsfiddle.net/michaelghayes/2rHgK/​​
This is untested, but I think it will work. Replace:
proto.__proto__ = new constructor(args)
With:
proto.__proto__ = {};
proto.__proto__.prototype = constructor.prototype;
constructor.apply(proto.__proto__, args);
Take note that __proto__ is deprecated.
its better not to attach things to the object prototype and just set up the inheritance manually:
Model function() {
//init parent first because of chromes hidden classes
ParentClass.apply(this, [].slice.call(arguments))
//new instance properties
this.something = 'something'
}
Model.prototype = Object.create(ParentClass.prototype, {
constructor: {value: Model}
})
//Prototype props
Model.prototype.whatever = function(){return 'whatever'}
this also allows you to modify args before initing the parent since your new class shouldn't be restricted to using the exact same args as its parent

Javavscript change sub-class property on instantiation

if I have
myClass.prototype.subClass=
{
foo:false
}
when I create a new instance on an object how can I set foo to a different value each time, so how do I refer to that sub-class here
var newObj = new myclass();
Objects and arrays are not something which should be added to the prototype unless you want to share them with all instances.
As soon as you want properties of these objects to be different for each instances, you have to assign the object in the constructor (or in any other function) to the specific instance:
this.subClass = {
foo: true
// potentially other properties
};
That said, there might be cases were having a "default" object in the prototype might be reasonable, but you should not write to it.
Assigning the object in the constructor instead does not duplicate code and allows you to change it for each instance individually.
Update:
If you don't want to change the original constructor, you can either just add a new function to the prototype and call it whenever you instantiate an object:
MyClass.prototype.init = function() {
this.subClass = {
//...
};
};
and
var obj = new MyClass();
obj.init();
Or you really create a new constructor function:
function MySubClass() {
MyClass.apply(this, arguments);
// now create that object for each instance
this.subClass = {
foo: someValue
};
}
inherits(MySubClass, MyClass);
where inherits is defined as:
function inherits(Child, Parent) {
var Tmp_ = function() {};
Tmp_.prototype = Parent.prototype;
Child.prototype = new Tmp_();
Child.prototype.constructor = Child;
}
Then you will use MySubClass instead of MyClass to create the instances.
I think you missunderstand how prototype inheritence works because this question is a bit odd. But you should be able to access the foo property like any other:
newObj.subClass.foo = newValue

Categories