Skip to content

Instantly share code, notes, and snippets.

@ValentynaGorbachenko
Created October 4, 2016 21:39
Show Gist options
  • Save ValentynaGorbachenko/1e186a2f7b39eabad349cd4ffdf83d53 to your computer and use it in GitHub Desktop.
Save ValentynaGorbachenko/1e186a2f7b39eabad349cd4ffdf83d53 to your computer and use it in GitHub Desktop.
objects_inheritance created by ValentynaGorbachenko - https://repl.it/CcaY/9
//Objects
var literalObject = {
name: "literalObject",
property1: "some data", //string
property2: 3, // number
property3: [], //array
property4: {},
method1: function(){
var result = [];
for (var prop in this) {
if( this.hasOwnProperty( prop ) ) {
result.push(this.name+"." + prop + " = " + this[prop]);
}
}
return result.join(",\n");
},
method2: function(){ //function
return console.log("This object \'"+this.name + "\' has such own proprties and methods: \n" + this.method1());
}
}
//Calling the method
literalObject.method2();
//Parent class
function Parent(v1,v2){
this.val0 = 0;
this.val1 = v1;
this.val2 = v2;
}
//Inheriting from the literalObject
Parent.prototype = literalObject;
//Child class
function Child(v3, v4){
this.val3 = v3;
this.val4 = v4;
this.meth5 = function(){ return this.val0;};
}
//or we can type this line insead of line 38: this.meth5 = ...
//Child.prototype.meth5 = function(){ return this.val0; };
//creating an instance obj1 of a Child class that doesn't have access to the Parent and objectLiteral
var obj1 = new Child(33, 44);
//Establishing the inheritance between Child and Parent and literalObject as well
Child.prototype = new Parent();
//creating instances obj2 and obj3 of a Child class that have access to the Parent and literalObject properties and methods
var obj2 = new Child(3,4);
//adding own property name
obj2.name = "obj2";
var obj3 = new Child(333, 444);
//adding own property name
obj3.name = "obj3";
console.log("Calling the method2 on obj2 and obj3 that belongs to the literalObject")
obj2.method2();
obj3.method2();
console.log("The instance obj1 of the Child class doesn't have access to the Parent as well as to the literalObject");
console.log("obj1.meth5() is "+obj1.meth5()+'\n'+"obj1.property1 is "+obj1.property1+'\n'+ "obj1.val3 is "+obj1.val3);
console.log("Instances obj2 and obj3 of the Child class have access to the Parent")
console.log("obj2.meth5() is "+obj2.meth5()+'\n'+"obj2.val0 is "+obj2.val0+'\n'+"obj2.property1 is "+obj2.property1);
console.log("obj3.meth5() is "+obj3.meth5()+'\n'+"obj3.property1 is "+obj3.property1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment