Skip to content

Instantly share code, notes, and snippets.

@thecodejack
Last active December 23, 2015 10:09
Show Gist options
  • Save thecodejack/6619533 to your computer and use it in GitHub Desktop.
Save thecodejack/6619533 to your computer and use it in GitHub Desktop.
My Experiments with prototype.js
//create a object
var Person = {name:'Adi'};
//create another empty object
var apk = {};
apk.__proto__ === apk.prototype
//returns false
//just FYI prototype is available for functions
//but
Person.isPrototypeOf(apk)
//returns true. weird huh. Its coz __proto__ also acts as prototype object and also both are not same
//set Person as __proto__ object to apk
apk.__proto__ = Person
console.log(apk.name);
//returns 'Adi'
//change name property of apk
apk.name = 'ASK'
Person.name
//returns "Adi"
//change name property of __proto__
apk.__proto__.name = 'ASK'
Person.name
//returns "ASK"
function Person(){console.log('In Person')};
console.log(Person.prototype);
//returns Person {}
console.log(Person.__proto__);
//returns function Empty() {}
console.log(Person.__proto__ === Person.prototype);
//returns false
Person.prototype.fname = "ADI";
var person = new Person();
console.log(person.fname);
//returns 'ADI'
Per
console.log(person.__proto__ === Person.prototype);
//returns true
function Man(){console.log('In Man')};
Man.prototype = new Person();
//currently not setting constructor as people suggest
var man = new Man();
//prints In Man
console.log(man.fname);
//returns 'ADI'
man instanceof Man
//returns true
//confused? so why do we need contructor?
man instanceof Person
//returns true
//thatz why :)
Man.prototype.constructor
//returns function Person(){console.log('In Person')}
//will it help if i change constructor of Man
Man.prototype.constructor = Man
var man2 = new Man();
man2 instanceof Man
//returns true
man2 instanceof Person
//returns true
//well this doesn't solve our problem
//it seems reason being instanceof checks for constructor for all __proto__'s available down the chain
//so to test whether an object is direct instance we supposed
man2.__proto__.constructor.name === 'Man'
//returns true
man2.__proto__.constructor.name === 'Person'
//returns false
Person.prototype.friends =[];
var person1 = new Person();
var person2 = new Person();
person1.friends.push('Rambo');
person1.friends
//returns ["Rambo"]
person2.friends
//returns ["Rambo"]
//confused. But its expected isn't it? coz prototype in this case just assigns the reference to the objects.
//so suggested to avoid setting initial values using prototype
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment