, , , , , .
TL; DR:
. , , , "" , . , , , .
new , , "use strict"; , , new.
/, Factory
.
, , . , "" .
, , , , , . , , - , . ( , lol jk!)
@Domenic JavaScript , , ?
.
new , . , Prototype.
var Constructor = function () {
this.x = 0;
this.y = 0;
};
var A = new Constructor();
console.log(A instanceof Constructor );
, , . , , .
:
Constructor.prototype.color = 'yellow';
, Constructor, .color, .
var A = new Constructor();
console.log(A.color);
console.log(A.hasOwnProperty('color'));
JavaScript , , "" , , "" .
var A = new Constructor();
Constructor.prototype.food = 'bacon';
console.log(A.food);
, , , .
Constructor.prototype.number = 5;
A.calculate = function () {
return A.number * 5;
}
console.log(A.calculate());
Constructor.prototype.number = 'fishsticks';
console.log(A.calculate());
, , V8, " ". , . JavaScript V8
. .__proto__. Object.getPrototypeOf().
console.log(Object.getPrototypeOf(A.color));
, Crockford , , new. new , .
var A = Constructor();
console.log(A);
, , new.
var Constructor = function () {
"use strict";
this.x = 0;
this.y = 0;
}
var A = Constructor();
console.log(A);
Factory
. new "" "", , .
function factory () {
var obj = {
x: 0,
y: 0
}
return obj;
}
var A = factory();
, - , .
function factory () {
if ( new Date().getHours() < 8 ) {
return "can't create object. Need Coffe!"
};
var obj = {
x: 0,
y: 0
}
return obj;
}
var A = factory();
var A = factory();
, / . .
factory.prototype.foo = "bar";
A = factory();
console.log(A.foo); // undefined
, . , .
.
. TL; DR
, , - -.
:
JavaScript , , ?
vs Factory
JavaScript