Answer the question
In order to leave comments, you need to log in
How to solve the problem when creating an object prototype?
I create prototypes of the object, but the output is ugly.
Help me please
let Unit = {
constructor: function(type,name,force) {
this.type = type;
this.name = name;
this.force = force;
return this
},
greet: function() {
console.log(this.name[0].toUpperCase() + this.name.slice(1) + " ready!")
}
};
let Infantry = Object.create(Unit);
Infantry.constructor = function(type,name,force,infrantryPosibilities) {
Unit.constructor.apply(this,arguments);
this.infrantryPosibilities = infrantryPosibilities || [];
return this;
};
let romanInfantry = Object.create(Unit).constructor('infantry','Caesar Infantry', 15,[1,5,67]);
console.log(romanInfantry.greet())
/* Caesar Infantry ready!
(index):53 undefined */
// должна выдавать строку
console.log(romanInfantry) // constructor {type: "infantry", name: "Caesar Infantry", force: 15}
// должна выдавать объект romanInfantry
Answer the question
In order to leave comments, you need to log in
console.log(romanInfantry.greet())
/* Caesar Infantry ready!
(index):53 undefined */
// should produce a string
console.log(romanInfantry) // constructor {type: "infantry", name: "Caesar Infantry", force: 15}
// should produce a romanInfantry object
Infantry.constructor = function(type,name,force,infrantryPosibilities) {
Unit.constructor.apply(this,arguments);
this.infrantryPosibilities = infrantryPosibilities || [];
return this;
did not change the original Unit object . // создаёте конструктор класса Unit
function Unit(type,name,force) {
this.type = type;
this.name = name;
this.force = force;
}
// создаёте наследуемые свойства/методы Unit
Unit.prototype = {
constructor: Unit,
greet: function() {
console.log(this.name[0].toUpperCase() + this.name.slice(1) + " ready!")
}
};
// создаёте конструктор класса Infantry
function Infantry(type,name,force,infrantryPosibilities) {
Unit.call(this,type,name,force);
this.infrantryPosibilities = infrantryPosibilities || [];
}
// наследуете Infantry класс Unit и замещаете родительское свойство constructor, на новое
Infantry.prototype = Object.create(Unit.prototype, {
constructor: {
value: Infantry,
enumerable: true,
writable: true,
configurable: true
}
});
// создаёте новый экземпляр класса Infantry, наследника Unit.
let romanInfantry = new Infantry('infantry','Caesar Infantry', 15,[1,5,67]);
romanInfantry.greet();
console.log(romanInfantry);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question