[JS]如何理解JS中的类和对象

[JS]如何理解JS中的类和对象

--------------------------------------------------------------------------------------------

变量:*的  =>  属性:属于一个对象

函数:*的  =>  方法:属于一个对象

函数:

function a()

{

 console.log('a');

}

方法:

var arr = [1, 2, 3, 4];

arr.a = function()

{

  console.log('a');

}

===================================================

简单的例子:

  var arr = new Array(1, 2, 3);

  这里的Array就是类,arr就是对象。

理解this:

  arr = [1, 2, 3, 4];

  arr.a = 5;

  arr.showA = function()

  {

    console.log(this.a);  //this为arr

  }

  oDiv.onclick = function()

  {

    console.log(this);  //this为oDiv

  }

  this:当前发生事件的对象,当前方法属于谁就代表谁。

===================================================

混合方式构造对象:

  原则     => 构造函数:加属性

            原型:加方法

  对象命名规范 => 类名首字母大写

function CreatePerson(name, sex)  //构造函数

{

  //成员属性

  this.name = name,

  this.sex = sex,

}

CreatePerson.PRototype.showName = function()  //在原型里加方法

{

  console.log('My Name Is ' + this.name);

}

CreatePerson.prototype.showSex = function()

{

  console.log('My Sex Is ' + this.sex);

}

var obj = new CreatePerson('Cw', 'male');

var obj2 = new CreatePerson('Girl', 'female');

console.log(obj.showName == obj2.showName);   //true;

  //同一方法,不同对象,如果不使用原型添加则不相等

  //原型属于类,在对象中加入自己的属性、方法,原型修改将对已有对象产生影响。

  //给对象添加方法,影响当前; 给原型添加方法,影响一类。原型的缺陷:无法限制覆盖。

===================================================

为对象添加方法和属性(注意):

  事件处理中this的本质  =>  window

                  方法属于谁

  不能在系统对象中随意附加方法、属性,否则会覆盖已有方法、属性。

  object对象(空的)

     其它对象:Date,Array,RegExp    

     

function createPerson(name, sex)  //构造函数

{

  var obj = new Object();     //创建对象

  obj.name = 'Cw';         //添加

  obj.sex = 'male';

  obj.showName = function()

  {

    console.log('My Name Is ' + this.name);

  }

  obj.showSex = function()

  {

    console.log('My Sex Is ' + this.sex);

  }

  

  obj.showName();

  obj.showSex();

  return obj;          //返回对象

}

var obj = createPerson('Cw', 'male');

obj.showName();

obj.showSex();

缺点:如果要创建多个对象,多次调用方法,对象方法重复创建。  

===================================================

工厂方式:调用函数前加new,系统自动创建一个空对象并返回

function createPerson(name, sex)

{

  this.name = 'Cw';

  this.sex = 'male';

  this.showName = function()

  {

    console.log('My Name Is ' + this.name);

  }

}

var obj = new createPerson('Cw', 'male');

原型的使用:

var arr = new Array(12, 13);

var arr2 = new Array(14, 15);

Array.prototype.sum = function()

{

  var result = 0;

  for(var i = 0; i < this.length; i++)

  {

    result += this[i];

  }

  return result;

}

console.log(arr.sum());

console.log(arr2.sum());

Link:http://www.cnblogs.com/farwish/p/4055675.html

------------------------------------www.farwish.com------------------------------------