Constructor

当我们今天要储存个人的信息会使用到object,但仔细思考若有100位的话,是否太麻烦了

let persion1 = {    name: "Dennis",    age: 22,    phone: "090909090"}console.log(persion1)//{ name: 'Dennis', age: 22, phone: '090909090' }

这个时候就需要Constructor来帮助我们建立一个实体物件,Constructor很像是一个模板,藉由不同的内容去创造多个不同的实体,是不是方便很多呢

function Person(name, age, phone){    this.name = name    this.age = age    this.phone = phone}let a = new Person("Dennis",22) //new 是关键字 建立一个Person的实体console.log(typeof(Person)) //functionconsole.log(typeof(a)) //object    

奇怪为什么会有this?

function Person(name, age, phone){    this.name = name    this.age = age    this.phone = phone    this.fn = function(){        console.log(this)    }}let a = new Person("Dennis",22) //new 是关键字 建立一个Person的实体a.fn()/*Person {  name: 'Dennis',  age: 22,  phone: undefined,  fn: [Function (anonymous)]}*/

结果我们透过fn的function来输出什么是this,结果就是指向目前的物件拉


最后来做个简单的小应用吧

function Person(name, age, phone){    this.name = name    this.age = age    this.phone = phone    this.SayHi = function(){        console.log(`${this.name}说你好`)    }}let a = new Person("Dennis",22) //new 是关键字 建立一个Person的实体a.SayHi() //Dennis说你好

关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章