@batemanchris
var simpleObject = {
a: 'a'
};
What does it look like?
{
a: 'a'
}
Then why can I do this?
simpleObject.toString(); // where the crap does this function come from?
Every object in JS has an "internal" property called prototype, which is basically a pointer to another object.
When you try to access a property (or function) on an object, JS tries to find it on the object first, and if it doesn't find it, it looks at the prototype.
var simpleObject = {
a: 'a'
};
Reality
{
a: 'a',
__proto__: {
...
toString: function,
hasOwnProperty: function,
...
}
}
Note: Accessing the prototype with __proto__ is part of ES6
though you probably don't want to do it in real code - use Object.getPrototypeOf() instead
var Demo = function() {
...
};
Demo.prototype.doSomething = function() {
...
};
var Demo = function() {
this.prop = 'text';
};
Demo.prototype.action = function() {
alert(this.prop);
};
var myDemo = Demo();
myDemo; // undefined
myDemo.action() // ERROR
window.prop; // 'text'
var Demo = function() {
this.prop = 'text';
};
Demo.prototype.action = function() {
alert(this.prop);
};
var myDemo = new Demo();
myDemo; // { prop:'a', action:function }
window.prop; // undefined
myDemo.action(); // alerts "text"
var Demo = function() {
this.prop = 'text';
};
Demo.prototype.action = function() {
alert(this.prop);
};
var myDemo = new Demo();
var Demo = function() {
this.prop = 'text';
};
Demo.prototype.action = function() {
alert(this.prop);
};
var myDemo = new Demo();
Object.create(myProtoObject);
Creates a new, empty object – with its __proto__ set to myProtoObject.var obj = Object.create(null); // returns { }
obj.toString(); // ERROR
var Demo = function() {
this.prop = 'text';
};
Demo.prototype.action = function() {
alert(this.prop);
};
var myDemo = new Demo();
var Demo = {
init: function() {
this.prop = 'text';
},
action: function() {
alert(this.prop);
}
};
var myDemo = Object.create(Demo);
myDemo.init();