用Class关键字来批量生产对象,并通过new关键字实例化 封装工具函数及构造函数

10 阅读1分钟

//用class关键字创建一个类为students1类来批量创建的对象 class students1{ //constructor 登记类的基础信息 constructor(name,age,sex,id){//形参 this.name=name; this.age=age; this.sex=sex; this.id=id }

}
let s1=new students1('zhangsan',12,'男',1)//实参顺序不能颠倒 必须跟形参保持一致 //通过 new关键字实例化 通过传递的实参得到一个对象 console.log(s1)

function Com(){} //plus 加 Com.prototype.plus=function (a,b){ return a+b } //minus 减 Com.prototype.minus=function(a,b){ return a-b } //Com.prototype={} 不推荐,会覆盖 var c=new Com() // console.log(c.plus(1,2),'[c]')

//用class创建一个类 名为Stu的类来批量创建的对象 class Stu{ /** * constructor 是什么? * 是构造器:是一个构造函数 * 1.自动执行,当使用new关键字来创造这个对象的时候,就会自动执行 * 2.给对象登记初始信息,接收形参 * 3.this来在类中保存外部传入的参数 */

constructor(name,age,sex,className){
    this.name=name;
    this.age=age;
    this.sex=sex
    this.classname=22
    this.students=4
}
sayHi(){
    console.log(this.name+this.age+'打招呼')
}

} let res=new Stu('张三',12,'男') let res1=new Stu('李四',12,'男') res.sayHi() res1.sayHi() console.log(res) console.log(res1)

// 封装成了一个工具函数 => 共同特点 => 运算 var computed = (function(){ function plus(a, b) { return a + b; }

function minus(a, b) {
    return a - b;
}

function div(a, b) {
    return a / b;
}

function mul(a, b) {
    return a * b;
}

return {
    plus: plus,
    minus: minus,
    div: div,
    mul: mul
}

}())

// 对象:描述某一事物的集合 var stu = { name: '小明', age: 16, className: '3班' }

var comObject = { minus(){

},
XXX(){

},

}

// 构造函数 /**

  • 首字母大写,不是强制要求的,行业内的要求是大写
  • */ function Com() {} Com.prototype.plus = function (a, b) { return a + b; } Com.prototype.minus = function (a, b) { return a - b; } Com.prototype = {} // 不推荐,会覆盖

var c = new Com() var c1 = new Com() var c2 = new Com()

  • 万物皆对象 对象: 属性,方法 let 22 = { stu: ['小明','xiaoli'], sex: [''] }

let phone = { name: 'xxx', price: '1111' }