Creating a Class Method - javascript

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"));

Related

Why doesn't the setter method have any effect on other variables in my JavaScript object?

Can someone please explain why the "fullName" variable in my object does not change after the "setFirstName" setter method has changed the "firstName" variable to "NewFirstName". I am aware of the correct answer to this problem but I'm confused as to why the following solution does not also work.
This is a picture showing the below snippet being run
Here is the code:
<!DOCTYPE html>
<html>
<script>
var Person = function(firstAndLast) {
let firstName = firstAndLast.split(" ")[0];
let lastName = firstAndLast.split(" ")[1];
let fullName = firstName + " " + lastName;
// Getters
this.getFirstName = function() {
return firstName;
};
this.getLastName = function() {
return lastName;
};
this.getFullName = function() {
return fullName;
};
// Setters
this.setFirstName = function(first) {
firstName = first;
};
this.setLastName = function(last) {
lastName = last;
};
this.setFullName = function(name) {
fullName = name;
};
};
debugger;
var bob = new Person('Bob Ross');
console.log(bob.getFullName());
bob.setFirstName("NewFirstName");
console.log(bob.getFirstName());
console.log(bob.getFullName());
</script>
</html>
Because you're only calculating fullName once, it won't update dynamically.
You don't really want a variable for fullName, just a getter:
this.getFullName = function() {
return firstName + " " + lastName;
}
Remove
let fullName = firstName + " " + lastName;
Alternatively you can keep your variable and manually update it in both the setFirstName and setLastName functions, but really this is the kind of thing getters exist to do.

How to write JavaScript prototype chain

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);

JS using a closure replicate an private set object only available through get/accessor method

I'm trying to create a function that uses a closure to replicate an object.
accessing the getter property within a private function.
function Container(param) {
var person = {
firstName: 'Jimmy',
lastName: 'Smith',
get fullName() {
return this.firstName + ' ' + this.lastName;
},
set fullName (name) {
var words = name.toString().split(' ');
this.firstName = words[0] || '';
this.lastName = words[1] || '';
}
}
}
// Attempting to clone private getter don't know how to access it.
function objectClone(person) {
var orginal = person //Trying to access the private method
var clone = function cloneObj { Object.assign({}, original); }
clone.prototype.spillSecret = function() { alert(this.getfullName()); }
;}
It seems like you're trying to create a new instance of a Container. Firstly, we should fix up that code:
function Container(param) {
this.firstName = 'Jimmy';
this.lastName = 'Smith';
Object.defineProperty(this, 'fullName', {
get: function() {
return this.firstName + ' ' + this.lastName;
},
set: function(name) {
var words = name.toString().split(' ');
this.firstName = words[0] || '';
this.lastName = words[1] || '';
}
});
}
Now, to create a new Container object, we use new:
var person = new Container();
person will have the get and set methods for fullName on it.

How to put functionality into abstract function in JavaScript

I am trying to make it so that I can have some methods in a JavaScript object be inheritable by a child class, but I don't want to allow the parent class to be instantiated. Here is some code that I wrote to illustrate this:
/**
* Shows how basic abstraction works with JavaScript
*/
//Define the person object with a first name, last name, and an age
function Person(firstName, lastName, age) {
//Make it so that this object cannot be instantiated by identifying its constructor
if(this.constructor === Person) {
throw new Error("Can't instantiate an abstract class of type Person!");
}
//Assign instance variables
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
//Create simple get methods
this.getName = function(){
return this.firstName + " " + this.lastName;
}
this.getFirstName = function() {
return this.firstName;
}
this.getLastName = function() {
return this.lastName;
}
this.getAge = function() {
return this.age;
}
}
//Define the student constructor
function Student(firstName, lastName, age, subject) {
//Assign the instance variables including the new subject variable
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.subject = subject;
//Add a new function to get the subject from Student
this.getSubject = function() {
return this.subject;
}
}
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
//Testing the inheritance
var joe = new Student("Joe", "Shmo", 33, "Computer Science");
console.log("First Name: " + joe.getFirstName()); //The getFirstName() function is defined in the superclass
console.log("Subject: " + joe.getSubject()); //The getSubject() function is defined in the subclass
With this code I get an error when trying to call getFirstName on the Student object joe. It seems that it would be very useful to have getFirstName be inheritable by the subclass.
I really want to be able to define the getName function in the parent class so that I can then just have that functionality inherited by the subclasses such as Student. Is there any way to do that? I would really appreciate any help!
You need to define your methods in the Person prototype, not in an instance of Person. That way they will be copied when you do Object.create(Person.prototype):
/**
* Shows how basic abstraction works with JavaScript
*/
//Define the person object with a first name, last name, and an age
function Person(firstName, lastName, age) {
//Make it so that this object cannot be instantiated by identifying its constructor
if(this.constructor === Person) {
throw new Error("Can't instantiate an abstract class of type Person!");
}
//Assign instance variables
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
Person.prototype.getName = function(){
return this.firstName + " " + this.lastName;
}
Person.prototype.getFirstName = function() {
return this.firstName;
}
Person.prototype.getLastName = function() {
return this.lastName;
}
Person.prototype.getAge = function() {
return this.age;
}
//Define the student constructor
function Student(firstName, lastName, age, subject) {
//Assign the instance variables including the new subject variable
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.subject = subject;
//Add a new function to get the subject from Student
this.getSubject = function() {
return this.subject;
}
}
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
//Testing the inheritance
var joe = new Student("Joe", "Shmo", 33, "Computer Science");
console.log("First Name: " + joe.getFirstName()); //The getFirstName() function is defined in the superclass
console.log("Subject: " + joe.getSubject()); //The getSubject() function is defined in the subclass

JavaScript Inheritance constructor.prototype

I can't understand line 4.
If I write like derive.constructor.prototype,
The error will occur.
And also, What is base.apply(derive, baseArgs);?
I thought that I can do like base(baseArg) I couldn't do that.
function initializeBase(derive, base, baseArgs) {
base.apply(derive, baseArgs);
for(var prop in base.prototype) {
var proto = derive.constructor.prototype;
if(!proto[prop]) {
proto[prop] = base.prototype[prop];
}
}
}
var Member = function(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
};
Member.prototype.getName = function() {
return this.firstName + ' ' + this.lastName;
};
var SpecialMember = function(firstName, lastName, role) {
initializeBase(this, Member, [firstName, lastName]);
this.role = role;
};
SpecialMember.prototype.isAdministrator = function() {
return (this.role == 'Administrator');
};
var mem = new SpecialMember('Kotaro', 'Hayafune', 'Administrator');
document.writeln('Name: ' + mem.getName() + '<br>');
document.writeln('Administrator: ' + mem.isAdministrator());
Not sure what your variables contain here but usually if you want the prototype you would write:
var proto = derive.prototype;
and if you wanted the constructor you'd write:
var constr = derive.prototype.constructor;

Categories

Resources