Как реализовать цепочку функций?

Надо решить тестовой задание, не подскажите как сделать?

Представьте, что у нас есть квадратное поле-сетка, по которому ходит бродяга.
Напишите объект «Бродяга», содержащий его координаты и четыре метода, реализующих шаг бродяги вверх, вниз, вправо и влево.
Как реализовать в таком объекте цепочку вида:
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);
  • Вопрос задан
  • 3302 просмотра
Решения вопроса 2
Fesor
@Fesor
Full-stack developer (Symfony, Angular)
У вас хэш-мэпа с функциями, а не объект. То есть вам нужно из функции возвращать экземпляр вашего хэш мэпа или следить за тем что бы контекст вызова сохранялся
Но лучше так:
http://learn.javascript.ru/object-methods#функция-...
function Human(x, y) {
    this.x = x;
    this.y = y;
}
Human.prototype = {
    goUp: function () {
        this.y++;
        return this;
    }
    goDown: function () {
        this.y--;
        return this;
    }
    // ...
}


Так же можно отDRY-ить код:
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
Ответ написан
Petroveg
@Petroveg
Миром правят маленькие с#@&ки
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
});
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы