JS 设计模式

// Constructor 构造模式

function A() {
  this.name = 'Vue'
  this.age = 3
}

A.prototype.say = function () {
  console.log('hello')
}

var a = new A()
a.say()

A.prototype.do = function(something) {
  console.log('do ' + something)
}
a.do('work')

// ----------------------------------------------------------

class B {
  constructor(name = 'Vue', age = 3) {
    this.name = name
    this.age = age
  }
  todo() {
    console.log('todo something')
  }
  do(something) {
    console.log('do ' + something)
  }
}
var b = new B()
b.age
b.todo()
b.do('work')

// 静态方法
B.say = function() {
  console.log('hello world')
}
// 实例方法
b.hello = function() {
  console.log('hello vue')
}
// -------------------------------------------------------
var a = {
  name: 'Vue',
  age: 3,
  do: function(something = 'work') {
    console.log('do ' + something)
  }
}
a.todo = function() {
  console.log('todo something')
}
// ---------------------------------------------------------
var a = (function() {
  var name = 'Vue'
  var age = 3
  function say() {
    console.log('hello')
  }
  function todo(something) {
    console.log('do ' + something)
  }
  return {
    name: name,
    age: age,
    say: say,
    todo: todo
  }
})()

var b = (function() {
  return {
    num: 0,
    increment() {
      this.num++
    }
  }
})()

var c = (function() {
  var num = 0
  function increment() {
    this.num++
  }
  return {
    num: num,
    increment: increment
  }
})()

var d = (function() {
  var module = {}
  module.num = 0
  module.increment = function() {
    this.num++
  }
  return module
})()

var m = { name: 'Vue' }
var e = (function(module) {
  function hello() {
    console.log(module.name)
  }
  return {
    hello: hello
  }
})(m)

var g = 'React'
var f = (function() {
  function name() {
    console.log(g)
  }
  return {
    name: name
  }
})()
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1、写出 构造函数模式、混合模式、模块模式、工厂模式、单例模式、发布订阅模式的范例。 1、设计模式分类: 构造函数...
    抚年华轻过阅读 504评论 0 1
  • 关键词:类,实例,原型 构造函数定义: 构造函数用于创建特定类型的对象——不仅声明了使用的对象,构造函数还可以接受...
    RomainLiu阅读 385评论 0 1
  • *工厂模式factory *构造函数模式constructor *单例模式single *混合模式mixin *模...
    jrg_memo阅读 375评论 0 0
  • 1.什么叫做设计模式(基本概念) 在面向对象软件设计过程中,针对问题进行简洁而优雅的一种解决方案 设计模式是在某种...
    Jianshu9527阅读 349评论 0 3
  • 介绍 构造函数大家都很熟悉了,不过如果你是新手,还是有必要来了解一下什么叫构造函数的。构造函数用于创建特定类型的对...
    cbw100阅读 386评论 1 3