自定义对象

阅读: 3475    发布时间: 2018-01-22 16:09:54

JS支持自定义对象

对象直接量

我们可以通过属性名:值,来创建一个对象,如

 var test={
      a:1,
      b:2,
      c:function(){
          alert(this.a+this.b)
      }
  }

test.c();

test 就是一个对象,包含属性a和b,方法c,方法中要引用属性,需使用this

通过这种方式创建对象不能很好的进行代码复用,如我们要创建test2,test3,就需要复制一遍上述代码,我们可以通过构造函数模式创建对接

构造函数

所谓"构造函数",其实就是一个普通函数,但是内部使用了this变量。对构造函数使用new运算符,就能生成实例,并且this变量会绑定在实例对象上。

function  Person(name,sex){
    this.name=name;
    this.sex=sex;
    this.hello=function(){
    alert("hello: "+this.name)
}
}

var li=new Person("李德龙","男"),
    wang=new Person("王小二","男");

li.hello();
wang.hello();

alert(li.hello==wang.hello); ///false

每个实例都有一个constructor属性,指向他们的构造函数

 alert(li.constructor==Person);    //true

通过上述构造函数有一个问题,多个实例的hello方法都是一摸一样的,而每生成一个实例,就增加一个hello方法,占用内存,我们可以通过Prototype模式解决整个问题


Prototype模式

我们将上述构造函数进行如下改造

 function  Person(name,sex){
    this.name=name;
    this.sex=sex;
}

Person.prototype.hello=function(){
    alert("hello: "+this.name)
}

var li=new Person("李德龙","男"),
    wang=new Person("王小二","男");

li.hello();
alert(li.hello==wang.hello);   //true

Javascript规定,每一个构造函数都有一个prototype属性,指向另一个对象。这个对象的所有属性和方法,都会被构造函数的实例继承。

这意味着,我们可以把那些不变的属性和方法,直接定义在prototype对象上。

Prototype模式的验证方法

 isPrototypeOf()

该方法用来判断某个对象和实例的关系

function Cat(name,color){
    this.name=name;
    this.color=color;
}

var cat1=new Cat();

console.log(Cat.prototype.isPrototypeOf(cat1));   //true

 hasOwnProperty()

 每个实例都有一个hasOwnProperty()方法,用来判断某一个属性到底是本地属性,还是继承自prototype对象的属性。

console.log(cat1.hasOwnProperty('name'))  //true,本地属性为true

in运算符

用来判断某个属性是否属于某个对象,不管是不是本地属性

console.log('name' in cat1);    //true

in运算符还可以用来遍历某个对象的所有属性。

for(var pros in cat1){
    console.log(pros);  //name   color
}


上一篇:对象简介