age = 28;
var Person = function (opt) {
if(!opt) return false;
this.name = opt.name || '';
this.age = opt.age || '';
};
Person.prototype.get = function (str) {
return this[str]
};
Person.prototype.type = 'Person';
var p = new Person({
name: 'jon',
age: 27
});
// case bound
var get = p.get;
console.log(get('age'), get.call(p, 'age'));
// First returns 28 because default this is window
// Second returns 27 because this is p
console.log(p.get('age'));
// successfuly returns 27 because this is p and p.age is 27
// case inheritence
var Student = function (opt) {
var ar = [];
ar.push(opt);
Person.apply(this, ar); // call the Person constructor
};
Student.prototype = new Person(); // inherit all the methods from Person
Student.prototype.constructor = Student; // we want to copy all the methods but constructor
var s = new Student({
name: 'jon'
});
Student.prototype.type = 'Student'; // overwrite type
console.log(s.get('name'));
console.log(s.type, p.type);
console.log(s.constructor); // returns the function assigned to Person
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.