class Arithmetic {
constructor() {
this.value = 0;
}
sum(...args) {
this.value = args.reduce((sum, current) => sum + current, 0);
return this;
}
add(value) {
this.value = this.value + value;
return this;
}
subtract(value) {
this.value = this.value - value;
return this;
}
average(...args) {
this.value = args.length
? (this.sum(...args).value) / args.length
: undefined;
return this;
}
}
a = new Arithmetic()
a.sum(1, 3, 6) // => { value: 10 }
.subtract(3) // => { value: 7 }
.add(4) // => { value: 11 }
.value // => 11
// Console Output
// 11
var o = {
a: 2,
m: function() {
return this.a + 1;
}
};
console.log(o.m()); // 3
// When calling o.m in this case, 'this' refers to o
var p = Object.create(o);
// p is an object that inherits from o
p.a = 4; // creates a property 'a' on p
console.log(p.m()); // 5
// when p.m is called, 'this' refers to p.
// So when p inherits the function m of o,
// 'this.a' means p.a, the property 'a' of p
function Shape(){//from ww w.j a v a 2 s . co m
this.isDrawable = true;
}
Shape.prototype.getDrawable = function(){
return this.isDrawable;
};
function Rectangle(){
this.hasFourEdges = false;
}
//inherit from Shape
Rectangle.prototype = new Shape();
Rectangle.prototype.getFourEdges = function (){
return this.hasFourEdges;
};
var instance = new Rectangle();
console.log(instance.getDrawable()); //true
{
prop: "some value",
__proto__: {
foo: "bar",
constructor: ƒ doSomething(),
__proto__: {
constructor: ƒ Object(),
hasOwnProperty: ƒ hasOwnProperty(),
isPrototypeOf: ƒ isPrototypeOf(),
propertyIsEnumerable: ƒ propertyIsEnumerable(),
toLocaleString: ƒ toLocaleString(),
toString: ƒ toString(),
valueOf: ƒ valueOf()
}
}
}