Loosely Inheritance purpose - javascript

I found the following interesting method in the babel compiler in and im totally new to js:
export default function _inheritsLoose(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
subClass.__proto__ = superClass; } ;
So I assumed, its to generate loosely coupled inheritance between two objects and I tried the following:
I created two simple objects
class Human{
constructor(name, surname){
this.Name = name;
this.Surname = surname;
}
rennen(){
console.log("Ich renne...");
}
}
class Superhuman{
constructor(age, weight) {
this.Age = age;
this.Weight = weight;
}
ausruhen(){
console.log("Ich ruhe aus...");
}
}
Created them and logged prototype
var a = new Human("Max", "Mustermann");
var b = new Superhuman(4, 80);
console.log("Human");
console.log(Human.prototype);
console.log("Superhuman");
console.log(Superhuman.prototype);
As expected they have their own props and methods.
I used the _inheritsLoose method that i found
Human.prototype = Object.create(Superhuman.prototype);
Human.prototype.constructor = Superhuman;
Human.__proto__ = Superhuman;
and expected that the following line has to be true
// Expecting its true now???
console.log(Human.prototype === Superhuman.prototype);
and
// Expecting its available in Human now???
Superhuman.prototype.fly = () => console.log("I fly....");
But it did not work. So my question is what is the purpose of the _inheritsLoose method and what am I doing wrong?

Related

JavaScript/jQuery extend function which takes parameter [duplicate]

I am attempting to pass a test suite utilizing inheritance through JavaScript. Below is a snippet of the code I have so far:
var Infant = function() {
this.age = 0;
this.color = 'pink';
this.food = 'milk';
};
Infant.prototype.eat = function(){
return this.eat;
}
var Adolescent = function() {
this.age = 5;
this.height = 'short';
this.job = 'keep on growing';
};
I would like to inherit the food property from the Infant class and the eat method but my attempts have fallen short. my initial thought was to assign this.Adolescent = Infant.food; but that didn't work. I know I need to set Infant as the Superclass but I'm spinning my wheels
When using constructor functions for inheritance in JavaScript, you:
Make the prototype property of the "derived" constructor an object whose prototype is the prototype property of the "base" constructor.
Set the constructor property on the "derived" constructor's prototype property to point to the "derived" constructor.
Call the "base" constructor from the "derived" constructor with the correct this.
Like this:
var Infant = function() {
this.age = 0;
this.color = 'pink';
this.food = 'milk';
};
Infant.prototype.eat = function(){
return /*...something...*/; // Returning `this.eat` doesn't make any sense, that's the function we're in
};
var Adolescent = function() {
// #3 Give super a chance to initialize the instance, you can pass args if appropriate
Infant.call(this);
this.age = 5;
this.height = 'short';
this.job = 'keep on growing';
};
// Set up Adolescent's prototype, which uses Infant's prototype property as its prototype
Adolescent.prototype = Object.create(Infant.prototype); // #1
Object.defineProperty(Adolescent.prototype, "constructor", // #2
value: Adolescent,
writable: true,
configurable: true
});
// (In pre-ES5 environments that don't event have `Object.defineProperty`, you'd use
// an assignment instead: `Adolescent.prototype.constructor = Adolescent;`
Object.create was added in ES5, so it won't be present on obsolete JavaScript engines like the one in IE8. The single-argument version of it used above can be easily shimmed, though.
In ES2015 we have the option of doing it with the new class semantics:
class Infant {
constructor() {
this.age = 0;
this.color = 'pink';
this.food = 'milk';
}
eat() {
return /*...something...*/;
}
}
class Adolescent extends Infant { // extends does #1 and #2
constructor() {
super(); // #3, you can pass args here if appropriate
this.age = 5;
this.height = 'short';
this.job = 'keep on growing';
}
}

extending objects in Javascript

I'm kinda lost in getting the object extending to work. I have read dozens of sites related to this topic, but I'm still no wiser. It seems that everyone uses it's own approach to make this work, and so do I , I'm trying to find the best approach for extending/inheriting objects.
I am also aware that there are tons of frameworks/plugins out there to cover this functionality, but i'd just like to understand how it works in general. Not mentioning that most of these frameworks include lots of other stuff I may never use, hence I'm trying to make my own.
I was able to extend an object , everything seemed to be ok until I started adding methods to the target object. To understand the issue, please see the below example...
or just try this JSFiddle
The thing is, that after initializing the new instance of Rabbit object, I wasn't able to access Rabbit's method changeName.
And I don't understand why it's happening, i.e why it doesn't recognize the method.
[*] Please see my updated code below (also the JFiddle), everything now seems to be working ok.
Can anoyne please advise, if this is a good approach or what am I missing?
var Class = (function(NewClass){
if(NewClass.length != 0){
var extend = function(target, source, args) {
Object.getOwnPropertyNames(source).forEach(function(propName) {
if(propName !== "Extend")
{
Object.defineProperty(
target, propName,
Object.getOwnPropertyDescriptor(source, propName)
);
}
if (typeof source[propName] !== 'undefined'){
delete source[propName];
}
});
return target;
};
var inherit = function(source, args){
var baseClass = Object.getPrototypeOf(this);
baseClass.prototype = extend.call(this, baseClass, source, args);
};
if(NewClass.Extend){
var Class = function(){ //// New Class Constructor ////
if(typeof NewClass.Extend === 'function'){
NewClass.Extend.apply(this, arguments);
inherit.call(this, NewClass.Extend);
console.log(NewClass)
inherit.call(this, NewClass, arguments);
if(NewClass.Initialize){
NewClass.Initialize.call(this, arguments);
}
}
};
Class.prototype.constructor = Class;
return Class;
}
}
});
var Animal =(function(args){//// constructor ////
var self = this;
self.name = typeof args !== 'undefined' ? args.name : null;
self.bags = 0;
});
var Rabbit = new Class({
Extend: Animal ,
Initialize: function(){
console.log(this.name)
},
changeName: function(a){
console.log(this.name)
}
});
var LittleRabbit = new Rabbit({name: "LittleRabbit", type: "None"});
console.log(LittleRabbit instanceof Rabbit)
console.log(LittleRabbit)
LittleRabbit.changeName("alex");
your extend function work wrong, because Object.getPrototypeOf return prototype, so in more cases it object
var extend = function(source, args){
var baseClass = Object.getPrototypeOf(this);
source.apply(this, args);
//so here you just add property prototype to object, and this not same as set prototype to function.
baseClass.prototype = Object.create(source.prototype);
};
So you can fix this like in snippet below:
function Class(args) {
if (arguments.length != 0) {
var C = function() {
if (typeof args.Extend == 'function') {
args.Extend.apply(this, arguments)
}
if (args.Initialize) {
args.Initialize.call(this);
}
};
if (typeof args.Extend == 'function') {
C.prototype = Object.create(args.Extend.prototype);
}
Object.keys(args).filter(function(el) {
return ['Extend', 'Initialize'].indexOf(el) == -1
}).forEach(function(el) {
C.prototype[el] = args[el];
});
return C;
}
};
var Animal = (function(args) { //// constructor ////
var self = this;
self.name = typeof args !== 'undefined' ? args.name : null;
self.bags = 0;
});
var Rabbit = Class({
Extend: Animal,
Initialize: function() {
console.log(this.name);
},
changeName: function(a) {
this.name = a;
}
});
var LittleRabbit = new Rabbit({
name: "LittleRabbit",
type: "None"
});
console.log(LittleRabbit instanceof Rabbit);
console.log(LittleRabbit instanceof Animal);
console.log(LittleRabbit.name);
LittleRabbit.changeName('new little rabbit');
console.log(LittleRabbit.name);
I would suggest reading the MDN article detailing the JavaScript object model. It contains examples of "manually" subclassing:
function Employee() {
this.name = "";
this.dept = "general";
}
function Manager() {
Employee.call(this);
this.reports = [];
}
Manager.prototype = Object.create(Employee.prototype);
function WorkerBee() {
Employee.call(this);
this.projects = [];
}
WorkerBee.prototype = Object.create(Employee.prototype)
Translating your example to this style is simple:
function Animal(name) {
this.name = name;
this.bags = 0;
}
function Rabbit(name) {
Animal.call(this, name);
console.log(this.name);
}
Rabbit.prototype = Object.create(Animal.prototype);
Rabbit.prototype.changeName = function(name) {
this.name = name;
};
Then you can easily run your example, modified a bit:
var LittleRabbit = new Rabbit("LittleRabbit");
console.log(LittleRabbit instanceof Rabbit)
console.log(LittleRabbit)
LittleRabbit.changeName("new name");
Once you understand this, I'd recommend not building your own class creation mechanism and just use ES6 classes:
class Animal {
constructor(name) {
this.name = name;
this.bags = 0;
}
}
class Rabbit extends Animal {
constructor(name) {
super(name);
console.log(this.name);
}
changeName(name) {
this.name = name;
}
}
You can see this example in the Babel REPL. Some browsers/js runtimes natively support ES6 classes already, but you can use Babel to translate your code to ES5 for environments that don't yet.
As an aside, there is actually more that needs to be done to subclass completely correctly. A more complete example (that may not work in all environments) is this:
function Animal() {}
function Rabbit() {
Animal.call(this);
}
Rabbit.prototype = Object.create(Animal.prototype);
Rabbit.prototype.constructor = Rabbit;
Rabbit.__proto__ = Animal;
May ES6 class inheritance an option for you:
'use strict';
class Animal {
constructor( name ) {
this.name = name;
}
changeName( name ) {
this.name = name;
}
}
class Rabbit extends Animal {
constructor() {
super( 'rabbit' );
}
}
let littleRabbit = new Rabbit();
console.log( littleRabbit.name ); //log default name
littleRabbit.changeName( 'littleRabbit' ); //executing an method of animal class
console.log( littleRabbit.name ); //log changed name
You don't need the "overhead" for making OOP inheritance for old good javascript because there are "translators" out there which translate your es6 code to es5 code. For Example babel: https://babeljs.io/
I think it is worth to give it a try...

Javascript Object.Prototype vs Object.anything

I'm trying to wrap my head around the JavaScripts prototype object and after some testing I saw that setting Object.prototype to parent Object.prototype or setting it to parent Object.a can seemingly yield the same results.
Below is some code to explain this better.
function Person(name) {
this.name = name;
}
Person.a = {};
Person.a.getName = function(){
return this.name;
}
Person.prototype.getName = function(){
return this.name;
}
function Male(name) {
this.gender = "male";
this.name = name;
return this;
}
function Female(name) {
this.gender = 'female';
this.name = name;
return this;
}
Male.prototype = Person.a;
Female.prototype = Person.prototype;
var m = new Male("levi");
var f = new Female("cho");
f.getName(); //cho
m.getName(); //levi
I think I'm missing a main component of how the prototype object works but I'm not sure what.
Any help would be really greatly appreciated.

Problem using the prototype chain

If I have a constructor that takes a number of arguments:
var Mammal = function(name, weight) {
this.name = name;
this.weight = weight;
}
Mammal.prototype.makeSound = function(sound) {
alert(sound);
}
Mammal.prototype.getName = function() {
return this.name;
}
and I want to do some inheritence:
var Human = function(name,weight,language,location) {
//code
}
Human.prototype = new Mammal();
In the last line here isn't the Human prototype getting assigned undefined for the name and weight parameters? I see this code all the time....I know that the Human constructor is being fed the name and weight params but it seems messy that the prototype is getting these undefined values. I know this only works because javascript is slack enough to allow you to do this. Is there a way to get round this?
What bothers you exactly?
Human.prototype = new Mammal();
alert( Human.prototype.name ); // undefined
alert( Human.prototype.foo ); // undefined
You can consider them as not being there. The reason why you're not writing:
Human.prototype = Mammal.prototype;
Is because the Mammal constructor can add methods that are not on the prototype object.
var Mammal = function(name, weight) {
this.name = name;
this.weight = weight;
this.somefun = function() {
// this can't be inhereted by
// Mammal.prototype
}
}
In order not to reapeat yourself you can use Constructor Chaining:
var Human = function(name,weight,language,location) {
this.language = language;
this.location = location;
// call parent constructor
Mammal.apply(this, arguments);
}
This seems to be more straightforward, isn't it? You call the parent constructor to deal with the name and weight parameters, and you only care about Human specific things in the Human constructor.
i think i've seen something like this once:
var Human = function(name,weight,language,location) {
Mammal.call(this, name, weight);//calls the parent constructor
this.language = language;
this.lcoaiton = location;
}
Human.prototype = new Mammal();

how do i namespace pseudo-classical javascript

I have some simple OO code I've written that I'm playing with:
//define a constructor function
function person(name, sex) {
this.name = name;
this.sex = sex;
}
//now define some instance methods
person.prototype.returnName = function() {
alert(this.name);
}
person.prototype.returnSex = function() {
return this.sex;
}
person.prototype.talk = function(sentence) {
return this.name + ' says ' + sentence;
}
//another constructor
function worker(name, sex, job, skills) {
this.name = name;
this.sex = sex;
this.job = job;
this.skills = skills;
}
//now for some inheritance - inherit only the reusable methods in the person prototype
//Use a temporary constructor to stop any child overwriting the parent prototype
var f = function() {};
f.prototype = person.prototype;
worker.prototype = new f();
worker.prototype.constructor = worker;
var person = new person('james', 'male');
person.returnName();
var hrTeamMember = new worker('kate', 'female', 'human resources', 'talking');
hrTeamMember.returnName();
alert(hrTeamMember.talk('I like to take a lot'));
Now this is all well and good. But I'm confused. I want to include namespacing as part of my code writing practice. How can I namespace the above code. As it is now I have 2 functions defined in the global namespace.
The only way I can think to do this is to switch to object literal syntax. But then how do I implement the pseudo-classical style above with object literals.
You could for example do following:
var YourObject;
if (!YourObject) {
YourObject = {};
YourObject.Person = function(name, sex) {
// ...
}
YourObject.Person.prototype.returnName = function() {
// ...
}
// ...
}
You don't have to use object literals, at least, not exclusively.
Decide on the single global symbol you'd like to use.
Do all your declaration work in an anonymous function, and explicitly attach "public" methods as desired to your global object:
(function(global) {
// all that stuff
global.elduderino = {};
global.elduderino.person = person;
global.elduderino.worker = worker;
})(this);
I may not be completely understanding the nuances of your issue here, but the point I'm trying to make is that Javascript makes it possible for you to start with your symbols being "hidden" as locals in a function, but they can be selectively "exported" in various ways.

Categories

Resources