/**
* OOP: ch.4 - Constructors and Prototypes
* =====================================================
* Constructors are Functions
*/
/*
* Constructor:
* ====================
* Objects created with the same constructor contain the same
* properties and methods.
*/
//Person Contstructor
function Person(name){
//props
this.name = name;
this.sayName = function(){
return this.name
}
/*
* You can also explicitly call return inside of a constructor.
* If the returned value is an object, it will be returned
* instead of the newly created object instance. If the returned
* value is a primitive, the newly created object is used and
* the returned value is ignored.
*/
//return ???
}
var p1 = new Person();
var p2 = new Person();
// show objs
console.log("Person => p1: ", p1);
console.log("Person => p2: ", p2);
/*
* you are advised to use instanceof to check the
* type of an instance. This is because the constructor
* property can be overwritten and therefore may not
* be completely accurate.
*/
// instance of Person?
console.log("p1 instanceof Person => ", p1 instanceof Person); //true
console.log("p2 instanceof Person => ", p2 instanceof Person); //true
// constructor?
console.log("p1.constructor: ", p1.constructor); // function
console.log("p1.constructor === Person: ", p1.constructor === Person); //true
console.log("p2.constructor: ", p2.constructor); //function
console.log("p2.constructor === Person: ", p2.constructor === Person); //true
console.log('----------------------------------------------------------------------------------------------------------');
//ES5 Person Constructor
function es5Person(name) {
//props
Object.defineProperty(this, "name", {
get: function() {
return name;
},
set: function(newName) {
name = newName;
},
enumerable: true,
configurable: true
});
//return 5;
}
//Person methods on the prototype
es5Person.prototype = {
//constructor:...
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.