How does toString work in js?
-
var user = { firstName: 'Василий', toString: function() { return 'Пользователь ' + this.firstName; } }; console.log(user);
Why does it display not what is in the toString function, but the object itself? How does it work in js?JavaScript Dominick Bradford, Aug 8, 2019 -
Because toString is a method, the method is called when you access it. To get the result of executing an object method, you need to refer to it.
console.log (user.toString ());
Carter Duncan -
function validator(value) {
return {
equal(array) {
if(array.toString() === value.toString()) {
return true;
} else {
return false;
}
},
isArray() {
if(Array.isArray(value)) {
return this;
} else {
return false;
}
},
isString() {
if(typeof value === "string") {
return true;
} else {
return false;
}
},
isNumber() {
if(typeof value === "number") {
return true;
} else {
return false;
}
}
}
}
console.log(validator('1').isArray()); // false
console.log(validator([]).isArray().equal([1, 2, 3])); // false
console.log(validator([1, 2, 3]).isArray().equal([1, 2, 3])); // true
console.log(validator('1').isString()); // true
console.log(validator('1').isNumber()); // falseAnonymous
2 Answers
Your Answer
To place the code, please use CodePen or similar tool. Thanks you!