Prototype in JS
by John Wick
JavaScript
/**
https://hackernoon.com/prototypes-in-javascript-5bba2990e04b
**/
console.clear();
// human constructor
function Human(firstName, lastName) {
this.firstName = firstName
this.lastName = lastName
this.fullName = function() {
return this.firstName + " " + this.lastName;
}
}
var person1 = new Human("Virat", "Kohli");
var person2 = new Human("JOhn", "Doe");
console.log('Human:',Human); // function Human() ....
console.log('Human.prototype:',Human.prototype); // Object {.....}
console.log('person1.__proto__:',person1.__proto__); // Object {.....}
console.log(person1.fullName()) // Virat Kohli
console.log(person2.fullName()) // JOhn Doe
console.log('1:', Human.prototype === person1.__proto__) // true
console.log('2:',person1.__proto__ === person2.__proto__) // true
console.log('3:',person1 == person2) // false
var obj = {
foo: function() {
return this;
}
};
console.log('obj.foo() === obj :',obj.foo() === obj);
console.log('obj:',obj);
console.log('obj.foo():',obj.foo());
function phone1() {
return function brand() {
return 'samsung'
}
}
console.log('phone =>', phone1()() );
function phone2() {
return function() {
return 'asus'
}
}
console.log('phone =>', phone2()() );
console.log(phone1() === phone2())
function foo() {
this.hello = 'helloworld';
return this;
}
console.log('foo() =>', foo()); // window
console.log('window =>', window)
console.log('foo() === window =>', foo() === window )
console.log('new foo() =>',new foo())
console.log('foo() === new foo() =>', foo() === new foo() );
console.log('foo().hello =>', foo().hello); // window
console.log('new foo().hello =>',new foo().hello)
function foto() {
this.hello = 'helloworld';
}
foto.prototype.testFunction = function (test){
return this.hello;
}
tempfunction = foto.prototype.testFunction
foto.prototype.testFunction = function wrappedFunction (test) {
this.hello = "helloworldpatched";
console.log('inside patched');
return tempfunction.apply(this, arguments);
/*...