构造函数和实例化

  前言

30b80aa24e74c97c3311295eac66fd33.png

  我是歌谣 最好的种树是十年前 其次是现在 今天继续给大家带来的是构造函数和实例化的讲解

  环境配置

078bc128fd636418ccd8cb8b211f1a3e.png

npm init -y
yarn add vite -D

 修改page.json配置端口

6b7d34f80dc0fe8c0c7787c7d80a6085.png

{
  "name": "demo1",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "vite --port 3002"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "vite": "^4.4.9"
  }
}

 案例1

779e09e1c0fec38dc5ba0f2e34e926f5.png

console.log("geyao")
var teacher={
    name:"geyao",
    age:18,
    sex:"male",
    height:176,
    weight:130,
    teach:function(){
        console.log("wo hui jiaoshu")
    },
    eat:function(){
        console.log("wo hui eat")
    }
}

 案例2

1b09937cbecc9a7bc58627f653bd0162.png

var attendance={
    students:[],
    total:6,
    join:function(name){
        this.students.push(name)
        console.log(this.students)
        if(this.students.length===this.total){
            console.log(name+"到课,学生已经全部到齐")
        }else{
            console.log(name+"到课,学生已经未到齐")
        }
    },
    leave:function(name){
        var idx=this.students.indexOf(name)
        if(idx!==-1){
            this.students.splice(idx,1)
        }
        console.log(name+"早退")
        console.log(this.students)
    }
}
attendance.join("歌谣")
attendance.join("方方")
attendance.join("康康")
attendance.leave("轩轩")

 运行结果

5aadad421efbfe6e3d947152d638ae35.png

e9b532e65c49cad54eed7ac246cb0548.png

案列3

7a49a338daa0c53269e101260e9b3a3c.png

function Teacher(){
    this.name="geyao",
    this.age="男"
    this.smoke=function(){
        console.log("wo hui smoking")
    }
}
var teacher1=new Teacher()
var teacher2=new Teacher()
teacher1.name="方方"
console.log(teacher1,teacher2)

 运行结果

44a40894d80cfe8a4acc2797cacfa538.png

ca2029d1cf0a4ff368bc0b8249c60c64.png

 案例4

c3234e44e184f64d0e9c6e51434040a5.png

function Teacher(opt){
    this.name=opt.name,
    this.sex=opt.sex,
    this.weight=opt.weight,
    this.course=opt.course
    this.smoke=function(){
        this.weight--
        console.log("wo hui smoking")
    },
    this.eat=function(){
        this.weight++
    }
    
}
var teacher1=new Teacher({
    name:"晓晓",
    sex:"男",
    weight:130,
    course:"java"
})
var teacher2=new Teacher({
    name:"晓晓",
    sex:"男",
    weight:130,
    course:"java"
})
console.log(teacher1,teacher2)

 运行结果

52dee7a8259b83d5c86e08a755a30f15.png

65ed1cc9eebd05a91083a7883f235956.png

e3a0f748321fbae8ed10fbd569349076.png

点击上方蓝字关注我们

下方查看历史文章

a63b93b456363397c76e54a1f777c6a3.png

立即执行函数

闭包

前端预编译流程

递归

函数参数默认值

posted @ 2023-11-07 08:00  前端导师歌谣  阅读(7)  评论(0编辑  收藏  举报  来源