viviannow / autoProject

【个人】各种资料待整理
2 stars 1 forks source link

面向对象 #7

Open viviannow opened 8 years ago

viviannow commented 8 years ago
// 工厂模式 常用
function Person(name, gender, age) {
 var obj       = Object();
 obj.name   = name;
 obj.gender = gender;
 obj.age      = age;
 obj.tellAge = function () {
   console.log(this.age);
 };
 return obj;
}

var puya = new Person('PuYart', 'male', '21');
puya.tellAge();
viviannow commented 8 years ago
// 构造函数模式
function Person(name, gender, age) {
  this.name = name;
  this.gender = gender;
  this.age = age;
  this.tellAge = function () {
    console.log(this.age);
  };
}

var puya = new Person('PuYart', 'male', '21');
puya.tellAge();
viviannow commented 8 years ago
// 原型链(+构造函数)模式 很常用
function Person(name, gender, age) {
  this.name = name;
  this.gender = gender;
  this.age = age;
}

Person.prototype.tellAge = function () {
    console.log(this.age);
};

var puya = new Person('PuYart', 'male', '21');
puya.tellAge();
viviannow commented 8 years ago

// ES6 中启用了关键字 class

class Person {
  constructor(name, gender, age) {
    this.name = name;
    this.gender = gender;
    this.age = age;
  }
  tellAge() {
    console.log(this.age);
  }
}

var puya = new Person('PuYart', 'male', '21');
puya.tellAge();
viviannow commented 8 years ago

对象在本质上是没有名称的,函数本身也是一种对象

函数是一咱包含了可执行代码,并能够被其它代码调用的特殊的对象

JS的对象是内存中的实体,保持着某种状态,用于编程操作的目标对象

JS的对象是一个名称与值配对的集合 ,JS对象可以定义为属性的集合

viviannow commented 8 years ago

JS对象的属性值可以由函数指定

JS具备一种称为原型链的构造,实现了类似于类的继承能力

viviannow commented 8 years ago

对象字面量表达式 属性名:标识符,字符串或数字 属性值:任意的值或对象

var obj = {
  x:2,
 color:{
      r:255,
      g255,
      b:255
 }
}

obj.x;
obj.color.r;

括号访问属性: obj['x']; obj['x'] = 5;