JSFiddle - React, Tailwind, and code Playground
Implementing new Keyword
by nickadeemus2002
JavaScript
/**
* implement the new keyword
*/
function customNew(constructor) {
//create object Object
var obj = {};
// create arguments array
var argsArray = Array.prototype.slice.apply(arguments);
// SET constructor prototype
Object.setPrototypeOf(obj, constructor.prototype);
//return instance
return constructor.apply(obj, argsArray.slice(1)) || obj;
}
function Person(firstName, location) {
this.firstName = firstName;
this.location = location;
this.age = null;
}
Person.prototype = {
constructor: Person,
getName: function() {
return this.name;
},
resetName: function(name) {
this.firstName = name;
},
getAge: function() {
return this.age;
},
setAge: function(age) {
this.age = age;
},
getLocation: function() {
return this.location
}
};
//this should be an instance of Person
var chris = customNew(Person, "Chris", "NYC");
chris.setAge(45);
console.log('chris.getAge() => ', chris.getAge());
console.log("chris => ", chris);
console.log(this.firstName);
console.log(this.location);