Relationship Between Instance Objects and Constructors
- Instance objects are created through constructors—the process of creation is called instantiation.
- How to determine whether the object is of this data type?
- Instance object through constructor. Constructor == constructor name
//自定义构造函数
function Person(name,age) {
this.name=name;
this.age=age;
}
//实例化对象
var per=new Person("小明",15);
//通过构造器判断对象是不是属于Person的实例
console.dir(per.constructor===Person);//true
- Object instanceof constructor name
//自定义构造函数
function Person(name,age) {
this.name=name;
this.age=age;
}
//实例化对象
var per=new Person("小明",15);
//通过instanceof判断对象是不是属于Person的实例
console.dir(per instanceof Person);//true
- Drawbacks of constructors
//自定义构造函数
function Person(name,age) {
this.name=name;
this.age=age;
}
function Student(sex) {
this.sex=sex;
}
//改变原型指向
Student.prototype=new Person();
//实例化对象
var stu=new Student();
//通过构造器判断stu的指向是不是Student
console.dir(stu.constructor==Student);//false
console.dir(stu instanceof Student);//true
Summarize:
Inheritance will change the pointer of the constructor, so it is not recommended to use the constructor constructor to judge whether the object is an instance of a constructor. It is recommended to use instanceof to judge