Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Genzhen opened this issue Sep 9, 2021 · 2 comments
Open
Labels
JavaScript teach_tag

Comments

@Genzhen
Copy link
Collaborator

Genzhen commented Sep 9, 2021

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

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

扫描下方二维码,收藏关注,及时获取答案以及详细解析,同时可解锁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();
@Genzhen Genzhen added the JavaScript teach_tag label Sep 9, 2021
@yangchunxia728
Copy link

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

@DavidQinqianWu
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
JavaScript teach_tag
Projects
None yet
Development

No branches or pull requests

3 participants