构造函数和实例化

2023-11-07 10:47:52 浏览数 (1)

前言

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

环境配置

代码语言:javascript复制
npm init -y
yarn add vite -D

修改page.json配置端口

代码语言:javascript复制
{
  "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

代码语言:javascript复制
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

代码语言:javascript复制
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("轩轩")

运行结果

案列3

代码语言:javascript复制
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)

运行结果

案例4

代码语言:javascript复制
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)

运行结果

0 人点赞