欢迎光临散文网 会员登陆 & 注册

千锋web前端开发项目教程_1000集完全零基础入门HTML5+CSS3+JS到

2023-07-12 12:05 作者:阿木木1214  | 我要投稿

ES5 方法创建类

js运用了面向对象的思想,但是却没有类的语法

解决方案:用函数模拟类,被当作类的函数本质是构造函数

  function Student(name,age,score){

  this.name = name;

    this.age = age;

    this.score = score;

    this.doHomework = function(){

console.log("doHomework");

    }

    this.eat = function (){

      console.log("eat");

}

    当一个成员函数要使用其他的成员,必须添加前缀this

    this.showValue = function(){

      console.log(this.name,this.age,this.score)

      this.eat()

      this.doHomework()

    }

  }

let s1 = new Student("aa",30,100);


普通函数与构造函数的区别:

   1.习惯上构造函数首字母大写

     2.构造函数必须和new连用

     3.构造函数不能添加return,因为自动返回的是地址

ES6 创建类

class 类名{

  //构造函数 -> new时调用的函数

  constructor(参数列表){

     

  }

  去掉function的普通函数

}

千锋web前端开发项目教程_1000集完全零基础入门HTML5+CSS3+JS到的评论 (共 条)

分享到微博请遵守国家法律