How to write JavaScript prototype chain - javascript

How to create an object of Manager with name "joe" and create subordinate "John" and add Salary to John.
Ex. var result = new Manager("Joe").getSubordinate("John").addSalary(10000);
function Manager(name){
this.name = name;
this.getSubordinate = function(submane){
return submane;
}
}
var result = new Manager('Joe');
I am able to write down so far.

if you want to chain the functions you need to return the objects like if you have a class Manager and one of Ordinate:
function Manager(name){
this.name = name;
this.subordinate = {John : new Subordinate('John')};
this.getSubordinate = function getSubordinate(subName){
return this.subordinate[subName];
};
}
function Subordinate(name){
this.name = name;
this.salary = 0;
this.addSalary = function addSalary(salary){
this.salary = salary;
return salary;
};
}
var result = new Manager('Joe').getSubordinate("John").addSalary(10000);
but i think you want as a result a Manager object so I recomend to use this way
function Manager(name){
var self = this;
this.name = name;
this.subordinate = {John : new Subordinate('John')};
this.getSubordinate = function getSubordinate(subName){
return this.subordinate[subName];
};
this.addSalaryToSubordinate = function addSalaryToSubordinate(subName, salary){
self.getSubordinate(subName).addSalary(salary);
return self;
};
}
function Subordinate(name){
this.name = name;
this.salary = 0;
this.addSalary = function addSalary(salary){
this.salary = salary;
return salary;
};
}
var result = new Manager('Joe').addSalaryToSubordinate ("John", 10000);

Related

Creating a Class Method

function Person(firstName = "John", lastName = 'Doe', age = 0, gender = 'Male') {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.gender = gender;
this.sayFullName = function() {
return this.firstName + " " + this.lastName
};
}
Person.prototype.greetExtraTerrestrials = function(raceName) {
return `Welcome to Planet Earth ${raceName}`;
};
What is wrong with this code? Doesn't it create a class method called greetExtraTerrestrials?
Don't place that function on prototype, place that on Class itself like
Person.greetExtraTerrestrials = function(raceName) {
return `Welcome to Planet Earth ${raceName}`;
};
and call it like
Person.greetExtraTerrestrials('ABC');
You can do both! The difference in
class Person(...) {
...
}
Person.myFunction = function(val) { // This is a public function
return val;
}
Person.prototype.myFunction = function(val) { // This is a private function
return val;
}
is how you access it.
Access the public function :
var r = Person.myFunction("Hello!");
console.log(r);
Access the private function:
var person1 = new Person(...);
var r = person1.myFunction("Hello!");
console.log(r);
See also this question.
Actually it works, but firstly you need to create an instance of Person to be able call its methods. For example:
var john = new Person("John");
console.log(john.greetExtraTerrestrials("predator"));

Create an instance of object internally

I have tried to create an instance of object internally like the following:
var oo = function(){
return new func();
}
var func = function(){
this.name;
this.age;
};
func.prototype = {
setData: function(name, age){
this.name = name;
this.age = age;
},
getData: function (){
return this.name + " " + this.age;
}
}
When usage, I got an error oo.setData is not a function.
oo.setData("jack", 15);
console.log(oo.getData());
What's wrong in my code?
This happens because oo is not a "func", oo returns a new func. You could set the data using
oo().setData('jack',15);
But then you have no way of accessing it.
You could also use
var newfunc = oo();
newfunc.setData('jack',15);
newfunc.getData();
oo is a function to create a object.
var oo = function(){ //the oo variable is used to create func() objects
return new func();
}
var func = function(){ //function
this.name;
this.age;
};
func.prototype = { //define properties to func
setData: function(name, age){
this.name = name;
this.age = age;
},
getData: function (){
return this.name + " " + this.age;
}
}
//create instance
var myObject = oo();
//or
var myObject = new func();
//Use
myObject.setData("jack", 12);
//Get a property
console.log(myObject.getData())

Accessing this variable from method instance

How do you access the this object from another object instance?
var containerObj = {
Person: function(name){
this.name = name;
}
}
containerObj.Person.prototype.Bag = function(color){
this.color = color;
}
containerObj.Person.prototype.Bag.getOwnerName(){
return name; //I would like to access the name property of this instance of Person
}
var me = new Person("Asif");
var myBag = new me.Bag("black");
myBag.getOwnerName()// Want the method to return Asif
Don't put the constructor on the prototype of another class. Use a factory pattern:
function Person(name) {
this.name = name;
}
Person.prototype.makeBag = function(color) {
return new Bag(color, this);
};
function Bag(color, owner) {
this.color = color;
this.owner = owner;
}
Bag.prototype.getOwnerName = function() {
return this.owner.name;
};
var me = new Person("Asif");
var myBag = me.makeBag("black");
myBag.getOwnerName() // "Asif"
Related patterns to deal with this problem: Prototype for private sub-methods, Javascript - Is it a bad idea to use function constructors within closures?

Explain this Uncaught TypeError: Property 'x' of object [object Object] is not a function

Can someone please explain why I get the results I do in each of the following situations? I wish to understand why the outcomes are what they are regarding how JavaScript works with scope, if this is what the issue is. In the first example, my code functions properly.
var Employees = function(name, salary) {
this.name = name;
this.salary = salary;
this.addSalary = addSalaryFunction;
this.getSalary = function() {
return this.salary;
};
};
var addSalaryFunction = function(addition) {
this.salary = this.salary + addition;
};
var ceo = new Employees("Chris", 400000);
ceo.addSalary(20000);
document.write(ceo.getSalary());
If I move the addSalaryFunction into the Employees function, and below this.addSalary I get the Uncaught TypeError.
var Employees = function(name, salary) {
this.name = name;
this.salary = salary;
this.addSalary = addSalaryFunction;
this.getSalary = function() {
return this.salary;
};
var addSalaryFunction = function(addition) {
this.salary = this.salary + addition;
};
};
var ceo = new Employees("Chris", 400000);
ceo.addSalary(20000);
document.write(ceo.getSalary());
But if I move the addSalaryFunction above this.addSalary if works properly again. Although my IDE tells me that my local variable addSalaryFunction is redundant.
var Employees = function(name, salary) {
this.name = name;
this.salary = salary;
var addSalaryFunction = function(addition) {
this.salary = this.salary + addition;
};
this.addSalary = addSalaryFunction;
this.getSalary = function() {
return this.salary;
};
};
var ceo = new Employees("Chris", 400000);
ceo.addSalary(20000);
document.write(ceo.getSalary());
It's because you're trying to assign the function before it was created.
this.addSalary = addSalaryFunction; // there's no function yet
//...
var addSalaryFunction = function(addition) { // now there is, but too late
this.salary = this.salary + addition;
};
When you moved the variable assignment above the this.addSalary = addSalaryFunction, you're now creating the function before trying to reference it.
var addSalaryFunction = function(addition) { // here's the function
this.salary = this.salary + addition;
};
this.addSalary = addSalaryFunction; // now we can assign it
If you had used function declaration syntax instead, the first version would work, because the function declarations are "hoisted" (as they say) to the top of the variable scope.
this.addSalary = addSalaryFunction; // This now works because of the magic below
//...
// This is magically hoisted to the top
function addSalaryFunction(addition) {
this.salary = this.salary + addition;
}
Second method does not work because addSalaryFunction is being referenced before it has been declared.
You could eliminate some code and just declare:
this.addSalary = function(addition) {
this.salary = this.salary + addition;
}
In a much simpler form:
var foo = function() {
var x = y;
var y = 2;
return x;
};
var bar = function() {
var y = 2;
var x = y;
return x;
};
Obviously, bar() will return 2. foo, however, gets undefined when it looks for a value of y on the first line, so returns undefined. While variable declarations are hoisted to the top of their scope, variable initialisations are not.
It's a specific hoisting problem. Have a look at this explanation: http://www.sitepoint.com/back-to-basics-javascript-hoisting/

Why does one need to call the function in an Object (constructor) in order to use a method that uses .this (JavaScript)

var setAge = function (newAge) {
this.age = newAge;
};
// now we make bob
var bob = new Object();
bob.age = 30;
bob.setAge = setAge;
bob.setAge(50);
console.log(bob.age);
This works, but when I try to do this
var setAge = function (newAge) {
this.age = newAge;
};
var bob = new Object();
bob.age = 30;
bob.setAge(50);
console.log(bob.age);
it returns "bob.setAge() is not a function" in the compiler?
The second example doesn't work because you haven't defined setAge, as you have here bob.setAge = setAge;. You created a new Object(), not a new custom-defined object. You're using sorta hybrid code... this is how you could do "classes"
var MyObject = function (age) {
this.age = age;
var that = this;
this.setAge = function (newAge) {
that.age = newAge;
}
};
var foo = new MyObject(10);
alert(foo.age);
foo.setAge(20);
alert(foo.age);
You have created an object 'Bob', but that object does not have the method 'setAge' until you assign it.
You may want to look into doing something like this in your design:
function Person(){
this.age = 30;
this.setAge = function(age){
this.age = age;
return this;
}
}
var bob = new Person;
bob.setAge(20);
console.log(bob.age);

Categories

Resources