Skip to content

Instantly share code, notes, and snippets.

@siddharthray
Last active June 16, 2018 17:54
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 siddharthray/f8879660cf90af82fc73fedba52dd948 to your computer and use it in GitHub Desktop.
Save siddharthray/f8879660cf90af82fc73fedba52dd948 to your computer and use it in GitHub Desktop.
Prototypes
function Apple (type) {
this.type = type;
this.color = "red";
this.getInfo = getAppleInfo;
}
// anti-pattern! keep reading...
function getAppleInfo() {
return this.color + ' ' + this.type + ' apple';
}
var apple = new Apple('macintosh');
apple.color = "reddish";
alert(apple.getInfo());
var Person = {
name: 'Sidd',
age: 25,
hobbies: ['cricket', 'mma'],
greet: function() {
console.log('My name is ' + this.name + ' and I am ' + this.age + ' years old');
}
};
Person.greet();
var anotherPerson = Object.create(Person);
anotherPerson.name = 'Ray';
console.log(anotherPerson.age);
Object.prototype.greet = function() {
console.log('Hello World, I am ' + this.name + '!!');
}
var sidd = Object.create(Person);
var ray = Object.create(Person);
ray.name = 'Ray';
// console.log(sidd.name);
sidd.greet();
ray.greet();
function Person(age, name, boy) {
this.age = age;
this.name = name;
this.boy = boy
this.greet = function() {
console.log("Hello I am " + this.name)
}
}
Person.prototype.greet = function() {
console.log('Hello World');
}
Person.prototype.name = 'Ray';
var person = new Person();
person.name = 'Ray';
var anotherPerson = new Person();
person.greet();
anotherPerson.greet();
console.log(person.name);
var person = new Person(25, 'Sid', true);
var anotherPerson = new Person(25, 'Siddhu', true);
console.log(person);
console.log(anotherPerson);
var account = {
cash: 12000,
withdraw: function(amount) {
this.cash -= amount;
console.log('Withdrew ' + amount + ' and the new reserve is ' + this.cash);
}
}
Object.defineProperty(account, 'deposit', {
value: function(amount){
this.cash += amount;
}
});
account.deposit(3000);
account.withdraw(1000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment