JavaScript中的構(gòu)造函數(shù)和實(shí)例對(duì)象之間的關(guān)系(構(gòu)造器)
1.自定義構(gòu)造函數(shù)
function Person(name,age,sex) { this.name=name; this.age=age; this.sex=sex; this.eat=function () { console.log("吃"); }; }
2.創(chuàng)建對(duì)象
var per=new Person("小明",38,"女");
3.實(shí)例對(duì)象的構(gòu)造器
實(shí)例對(duì)象的構(gòu)造器是指向Person的,結(jié)果是true,所以,這個(gè)實(shí)例對(duì)象per就是通過(guò)Person來(lái)創(chuàng)建的
console.log(per.constructor==Person);//true
4.判斷這個(gè)對(duì)象是不是這種數(shù)據(jù)類型
console.log(per.constructor==Person); console.log(per instanceof Person);//推薦
5.總結(jié)
實(shí)例對(duì)象和構(gòu)造函數(shù)之間的關(guān)系:
1. 實(shí)例對(duì)象是通過(guò)構(gòu)造函數(shù)來(lái)創(chuàng)建的---創(chuàng)建的過(guò)程叫實(shí)例化
2.如何判斷對(duì)象是不是這個(gè)數(shù)據(jù)類型?
1) 通過(guò)構(gòu)造器的方式 實(shí)例對(duì)象.構(gòu)造器==構(gòu)造函數(shù)名字
2) 對(duì)象 instanceof 構(gòu)造函數(shù)名字
盡可能的使用第二種方式來(lái)識(shí)別
本篇博客來(lái)自于傳智播客視頻教程的總結(jié)以及筆記的整理,僅供學(xué)習(xí)交流,切勿用于商業(yè)用途
相關(guān)文章:
