Skip to content

单例模式 #458

@LittlebearHat

Description

@LittlebearHat

个人写法不习惯用class语法糖

const danli = function (name) {
  this.name = name;
  this.instance = null;
};
danli.prototype.getName = function () {
  console.log(this.name);
};
danli.getInstance = function (ret) {
  if (!this.instance) {
    this.instance = new danli(ret);
    //假如为null,创建一个构造函数,此时instance标记不为空,不用进行二次创建
  }
  return this.instance;
};
let a = danli.getInstance("a");
let b = danli.getInstance("b");
a.getName();
b.getName();
console.log(a === b); //他俩相同,因为没有二次创建

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions