javascript - 面向对象

要是直接百度,如何在 javascript 中创建一个对象,你能找到一堆这样的文章:《js 创建对象的 n 种方式》、《闭包的 n 种写法》……

咱们不参加考试,不要记那么多,整那么多写法,代码还不好维护。

就例举几个,在实际项目开发过程中,比较好的代码写法。

兼容语法 1

如果想兼容旧的浏览器,可以采用这种方式,采用了闭包的写法。

几乎不存在兼容性问题,除了代码缩进不好看,没什么缺点。

<!DOCTYPE html>
<html lang="CHN">
<head>
  <meta charset="utf-8">
  <title>demo</title>
</head>
<body>
</body>
<script>
    function Person() {
        var age = 3;
        var name = 'xiaomming';

        return {
            getAge: function () {
                return age
            }
            , setAge: function (a) {
                age = a;
            }
            , getName: function () {
                return name;
            }
            , setName: function (a) {
                name = a;
            }
        }
    }

    var person = new Person();

    console.log(person.getAge());
    console.log(person.getName());
</script>
</html>

兼容语法 2

如果觉得代码缩进不好看,可以采用这种方式。

<!DOCTYPE html>
<html lang="CHN">
<head>
  <meta charset="utf-8">
  <title>demo</title>
</head>
<body>
</body>
<script>
  function Person() {
    this.age = 3;
    this.name = 'xiaomming';
  }

  // 这种写法的缺点,是容易产生不规范的代码。
  // 比如:你离职之前,在这里写三五百行代码,其他人就看不懂 Person 是怎么定义的了。
  
  Person.prototype.getAge = function () {
    return this.age
  }
  Person.prototype.setAge = function (a) {
    this.age = a;
  }
  Person.prototype.getName = function () {
    return this.name;
  }
  Person.prototype.setName = function (a) {
    this.name = a;
  }

  var person = new Person();

  console.log(person.getAge());
  console.log(person.getName());
</script>
</html>

ES6 语法

ES6 有 class 的概念,可以采用下面这种写法。

跟闭包的写法相比,似乎没啥改进,重点是 ES6 还多了 extends 语法。

这估计会形成升级代码的动力,因为在旧的代码中,写继承是很麻烦的一件事。

<!DOCTYPE html>
<html lang="CHN">
<head>
  <meta charset="utf-8">
  <title>demo</title>
</head>
<body>
</body>
<script>
    class Person {
        age = 3;
        name = 'xiaomming';

        constructor() {
            console.log('构造函数')
        }

        getAge() {
            return this.age
        }

        setAge(a) {
            this.age = a;
        }

        getName() {
            return this.name;
        }

        setName(a) {
            this.name = a;
        }
    }

    class Student extends Person{
    }
    
    let student = new Student();

    console.log(student.getAge());
    console.log(student.getName());
</script>
</html>

posted on 2024-06-13 21:57  疯狂的妞妞  阅读(1)  评论(0编辑  收藏  举报

导航