Skip to content

Instantly share code, notes, and snippets.

@debugmodedotnet
Created November 20, 2020 17:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save debugmodedotnet/52aaac08e7c02e262b4c6c85d247cff1 to your computer and use it in GitHub Desktop.
Save debugmodedotnet/52aaac08e7c02e262b4c6c85d247cff1 to your computer and use it in GitHub Desktop.
code from jspoland2020 JavaScript talk
// // value of 'this' depends on how you are calling the function
var Dog = {
name :'foo',
eat : function(){
console.log(this);
}
}
var Cat = {
name :'my cat'
}
function Product(){
console.log(this);
return 9;
}
let a = Product() ; // function invocation pattern , value of 'this' is global object
let b = new Product(); // constructor invocation pattern , value of 'this' is newly created object
console.log(b);
Dog.eat(); // method value of 'this' is object before dot
Dog.eat.call(Cat); // apply, call, bind i.e indirect invocation pattern - this is always the first argument in the function
// __proto__ to link object
var Animal = {
name:'foo',
age : 9
}
var Dog = {
owner : 'koo',
canRun : true
}
Dog.__proto__ = Animal;
Object.defineProperty(Dog,'owner',{enumerable:false});
for(var p in Dog){
//console.log(Dog[p]);
console.log(p);
}
console.log(Object.keys(Dog));
// There are four ways object can be created in JavaScript
// object literal
// var Dog = {
// }
// Object.create
var Cat = Object.create(Dog)
// use class
function Product (title,price){
this.title = title;
this.price = price;
}
Product.prototype.color = 'blue';
//console.log(Product.prototype);
var p1 = new Product('p1',90);
var p2 = new Product('p2',20);
p1.color = "red";
console.log(p1.__proto__.color);
console.log(p2.color);
console.log(p1.constructor);
console.log(p2.constructor);
// when you create an object in javascript using constructor, that object is linked to prototype of the construcrtor
console.log(p1.constructor.prototype == p2.constructor.prototype);
console.log(p1.constructor.prototype == p1.__proto__);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment