JavaScript创建对象之单例、工厂、构造函数模式

// 单例模式 解决分组问题 让每个对象有自己的命名空间
var person1 = {
  name: "icss";
  age: 25;
};

var person2 {
  name: "sas";
  age: 26
}
// 工厂模式 实现同一事情的代码 放在一个函数中 其实就是函数的封装 体现了高内聚 低耦合
function createPerson(name, age) {
  var obj = {};
  obj.name = name;
  obj.age = age;
  obj.writejs = function() {
    console.log(this.name + "write js");
  }
return obj;
}
var p1 = createPerson("zhang", 26);
p1.writejs();

var p2 = createPerson("li", 26);
p1.writejs();

// 重载 js不同于java \ c#等强语言

// 构造函数模式
function CreateJsPerson(name, age) {
  this.name = name;
  this.age = age;
  this.writeJs = function() {
    console.log(this.name + 'write js');
  }
// 浏览器再把创建的实例默认的进行返回
}
var p1 = new CreateJsPerson('iceman', 25);
p1.writeJs();
var p2 = new CreateJsPerson('mengzhe', 26);
p2.writeJs();

// 检测是否属于类 需要用instanceof 而不能用 typeof(因为只能检测基本的数据类型)
function Fn() {
  this.x = 100;
  this.getX = function() {
    console.log(this.x);
  };
}
var f1 = new Fn;
console.log(f1 instanceof Fn); // --> true
console.log(f1 instanceof Array); // --> false
console.log(f1 instanceof Object); // --> true

// this js中主要研究的就是this 全局的this是window 就是浏览器对象

// 在JavaScript中主要研究的都是函数中this,但是并不是只有函数中才有this,全局的this是window。
//
// JavaScript中的this代表的是当前行为执行的主体,JavaScript中的context代表的是当前行为执行的环境。
//
// 首先明确:this是谁,和函数在哪里定义,在哪里执行都没有任何的关系,那么如何区分this呢?
//
// 函数执行,首先看函数名前面是否有".",有点话,"."前面是谁,this就是谁,没有的话,this就是window;
//
// 自执行函数中的this永远是window;
//
// 给元素的某一个事件绑定方法,当事件触发的时候,执行对应的方法,方法中的this是当前的元素。

posted @ 2017-01-17 12:25  言不可道尽  阅读(158)  评论(0编辑  收藏  举报