前言

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

环境配置

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

function Car(color,brand){
    this.color=color,
    this.brand=brand
    this.drive=function(){
        console.log("i am running")
    }
}
var car = new Car('黑色',"geyao")
console.log(car.color)
console.log(car.brand)
car.drive()

运行结果

前端歌谣-第贰拾玖课-构造函数和实例化原理_构造函数

案例2

function Car(color,brand){
    var me={};
    me.color=color;
    me.brand=brand
    return me
}
var car=new Car("red","geyao")
console.log(car.color)
console.log(car.brand)

运行结果

前端歌谣-第贰拾玖课-构造函数和实例化原理_构造函数_02