lgwebdream / FE-Interview

🔥🔥🔥 前端面试,独有前端面试题详解,前端面试刷题必备,1000+前端面试真题,Html、Css、JavaScript、Vue、React、Node、TypeScript、Webpack、算法、网络与安全、浏览器
https://lgwebdream.github.io/FE-Interview/
Other
6.76k stars 897 forks source link

Day384:JavaScript 中如何实现一个类?怎么实例化这个类? #1219

Open Genzhen opened 2 years ago

Genzhen commented 2 years ago

每日一题会在下午四点在交流群集中讨论,五点小程序中更新答案 欢迎大家在下方发表自己的优质见解

二维码加载失败可点击 小程序二维码

扫描下方二维码,收藏关注,及时获取答案以及详细解析,同时可解锁800+道前端面试题。


构造函数法

用 new 关键字生成实例对象

缺点是用到了 this 和 prototype,编写复杂,可读性差

function Mobile(name, price) {
  this.name = name;
  this.price = price;
}
Mobile.prototype.sell = function () {
  alert(this.name + ",售价 $" + this.price);
};
var iPhone = new Mobile("iPhone", 1000);
iPhone.sell();

Object.create 法

Object.create() 生成实例对象。

缺点是不能实现私有属性和私有方法,实例对象之间也不能共享数据

var Person = {
  firstName: "Mark",
  lastName: "Yun",
  age: 25,
  introduce: function () {
    alert("I am " + Person.firstName + " " + Person.lastName);
  },
};

var person = Object.create(Person);
person.introduce();

// Object.create 要求IE9,低版本浏览器可以自行部署
if (!Object.create) {
  Object.create = function (o) {
    function F() {}
    F.prototype = o;
    return new F();
  };
}

极简主义

消除 this 和 prototype,调用createNew() 得到实例对象

优点是容易理解,结构清晰,符合传统的面向对象编程的构造

var Cat = {
  age: 3, // 共享数据,定义在类对象内,createNew外
  createNew: function () {
    var cat = {};
    cat.name = "cat1";
    var sound = "didi"; // 私有属性,定义在createNew 内,输出对象外
    cat.makeSound = function () {
      alert(sound); // 暴露私有属性
    };
    cat.changeAge = function (num) {
      Cat.age = num; // 修改共享数据
    };
    return cat;
  },
};
var cat = Cat.crateNew();
cat.makeSound();

ES6 语法糖 class

用 new 关键字生成实例对象

class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
  toString() {
    return "(" + this.x + "," + this.y + ")";
  }
}
var point = new Point();
yangchunxia728 commented 2 years ago

使用构造函数实现, 使用es6 的Class实现 使用new 实例化

DavidQinqianWu commented 2 years ago

还是极简注意的代码不错 简单. 通过 cat.name 就是 Cat class 中的 public, cat 就是实例化被赋值的对象. 那后单独在 createNew里面声明的变量, 就是private