构造函数和实例化
前言
我是歌谣 最好的种树是十年前 其次是现在 今天继续给大家带来的是构造函数和实例化的讲解
环境配置
npm init -y
yarn add vite -D
修改page.json配置端口
{
"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
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
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
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
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)
运行结果
点击上方蓝字关注我们
下方查看历史文章