vagabond.goUp().goLeft().goDown().goDown().goRight();
var Human = {
constructor: function(top, left, right, bottom) {
this.top = top;
this.bottom = bottom;
this.left = left;
this.right = right;
return this;
},
goUp: function() {
return this.top;
},
goDown: function() {
return this.bottom;
},
goLeft: function() {
return this.left;
},
goRight: function() {
return this.right;
}
}
var vagabond = Object.create(Human).constructor(2,2,2,2);
function Human(x, y) {
this.x = x;
this.y = y;
}
Human.prototype = {
goUp: function () {
this.y++;
return this;
}
goDown: function () {
this.y--;
return this;
}
// ...
}
function coordsChangerFactory(prop, direction) {
return function () {
// тут можно добавить валидацию, мол что бы не вылазить за пределы поля
this[prop] += direction;
return this;
}
}
function Human(x, y) {
this.x = x;
this.y = y;
}
Human.prototype = {
goUp: coordsChangerFactory('y', +1),
goDown: coordsChangerFactory('y', -1),
goLeft: coordsChangerFactory('x', -1),
goRight: coordsChangerFactory('x', +1)
}
var man = new Human(4, 4);
man.goDown().goRight();
console.log('Coords is %dx%d', man.x, man.y); // Coords is 5x3
var Human = function (coords) {
this.top = coords.top || 0;
this.left = coords.left || 0;
};
Human.prototype = {
go: function (coords) {
this.top += coords.top || 0;
this.left += coords.left || 0;
return this;
},
goUp: function () {
return this.go({top: -1});
},
goDown: function () {
return this.go({top: 1});
},
goLeft: function () {
return this.go({left: -1});
},
goRight: function () {
return this.go({left: 1});
}
};
var vagabond = new Human({
top: 2,
left: 2
});
vagabond.goUp().goLeft().goDown().goDown().goRight();
vagabond.go({
top: 0,
left: 0
});