1.获取对象类型
关键词:对象.constructor.name
<script>
let obj = new Object();
console.log("使用typeof关键字获取的对象类型" + typeof obj);
console.log("使用 对象.constructor.name获取的对象类型" + obj.constructor.name);
let arr = new Array();
console.log("使用typeof关键字获取的对象类型" + typeof arr);
console.log("使用 对象.constructor.name获取的对象类型" + arr.constructor.name);
function Person() {
this.name = "lnj";
this.age = 34;
this.say = function() {
console.log(this.name, this.age);
}
}
let p = new Person();
console.log("使用typeof关键字获取的对象类型" + typeof p);
console.log("使用 对象.constructor.name获取的对象类型" + p.constructor.name);
</script>
控制台输出:
2.instanceof关键字
instanceof用于判断 “对象” 是否是指定构造函数的 “实例”
格式:实例对象 instanceof 构造函数
<script>
function Person() {
this.name = "lnj";
this.age = 34;
this.say = function() {
console.log(this.name, this.age);
}
}
function Cat() {
this.name = name;
}
let p = new Person();
let c = new Cat();
console.log(p instanceof Person);// true
console.log(p instanceof Cat);// false
</script>
只要 构造函数的原型对象出现在实例对象的原型链中都会返回true
<script>
function Person(myName) {
this.name = myName;
}
function Student(myName, myScore) {
Person.call(this, myName);
this.score = myScore;
}
Student.prototype = new Person();
Student.prototype.constructor = Student;
let stu = new Student();
console.log(stu instanceof Person); // true
</script>
3.isPrototypeOf属性
isPrototypeOf用于判断 一个对象是否是另一个对象的原型
<script>
class Person{
name = "lnj";
}
let p = new Person();
console.log(Person.prototype.isPrototypeOf(p)); // true
class Cat{
name = "mm";
}
console.log(Cat.prototype.isPrototypeOf(p)); // false
</script>
只要调用者在传入对象的原型链上都会返回true
function Person(myName) {
this.name = myName;
}
function Student(myName, myScore) {
Person.call(this, myName);
this.score = myScore;
}
Student.prototype = new Person();
Student.prototype.constructor = Student;
let stu = new Student();
console.log(Person.prototype.isPrototypeOf(stu)); // true
4.判断对象属性
in
in的特点: 只要类中或者原型对象中有, 就会返回true
<script>
class Person {
name = null;
age = 0;
}
Person.prototype.height = 0;
let p = new Person();
console.log("name" in p); // true
console.log("width" in p); // false
console.log("height" in p); // true
</script>
hasOwnProperty
特点: 只会去类中查找有没有, 不会去原型对象中查找
<script>
class Person {
name = null;
age = 0;
}
Person.prototype.height = 0;
let p = new Person();
console.log(p.hasOwnProperty("name")); // true
console.log(p.hasOwnProperty("height")); // false
</script>