Instanceof operator là gì?
Noun
Javascript
- ★
- ★
- ★
- ★
- ★
instanceof
Toán tử instanceof
Toán tử instanceof (instanceof operator) trong ngôn ngữ lập trình Javascript được sử dụng để kiểm tra xem một giá trị có phải là một thể hiện (instance) của một lớp (class) nhất định hay không. Nó được sử dụng ở cú pháp (syntax) "value1 instanceof value2" và trả về (return) một boolean. Ví dụ như code bên dưới:
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
const auto = new Car('Honda', 'Accord', 1998);
console.log(auto instanceof Car);
// expected output: true
console.log(auto instanceof Object);
// expected output: true
Bên dưới là code ví dụ thứ hai:
console.log(1 instanceof Number)
console.log(new Number(1) instanceof Number)
console.log("" instanceof String)
console.log(new String("") instanceof String)
Output:
false true false true
Learning English Everyday