前端开发Web前端之路@IT·互联网

读书笔记 | JavaScript创建对象

2016-09-09  本文已影响345人  Evelyn_Chan

参考资料

JavaScript高级程序设计(第3版)

一、理解对象

( 一)对象属性的分类

JS对象属性有两种类型:数据属性和访问器属性

1、数据属性

数据类型有四个描述其行为的特性:

2、访问器属性

访问器属性有如下4个特性:

(二)定义或修改对象属性

1、定义或修改数据属性

Object.definedProperty()和Object.definedProperties()是 ES5(ECMAScript5)特有的,部分浏览器不兼容。

2、定义或修改访问器属性

访问器属性不能直接定义,必须使用Object.definedProperty( )来定义。

(三)读取属性的特性

利用Object.getOwnPropertyDescriptor(obj,property)读取指定对象obj的属性property的值。

二、创建对象

JavaScript中可以使用以下7种模式来创建对象,其中“组合使用构造函数模式和原型模式”使用最广泛、认同度最高。

(一) 工厂模式

function createStudent(name,country){
    var o=new Object();
    o.name=name;
    o.country=country;
    o.sayName=function(){
        alert(this.name);
    };
    return o;
}
var student1=createStudent("evelyn","China");

缺点:没有解决对象识别的问题。

(二)构造函数模式

function Student(name,country){
    this.name=name;
    this.country=country;
    this.sayName=sayName;
}
function sayName{
        alert(this.name);
 }
var student1=new Student("evelyn","China");//student1既是Student的实例,也是Object的实例

1、关于构造函数

构造函数命名必须首字母大写,而非构造函数应该以一个小写字母开头。

2、缺点

对象的方法是全局的函数,但却只被某个对象调用。另外,如果某个对象有很多方法,就要定义许多全局函数,毫无封装性可言。

(三) 原型模式

function Student(){
}
Student.prototype={  
    constructor:Student, 
    name:"evelyn",
    country:"China",
    sayName:function(){
         alert(this.name);
    }
};
var student1=new Student();

1、关于原型

2、关于枚举

3、缺点

(四)组合使用构造函数模式和原型模式(最常用)

function Student(name,country){
    this.name=name;
    this.country=country;
}
Student.prototype={
    constructor:Person,    //重写了默认的prototype对象,constructor不再指向Person(而是指向Object),因而重新设置指向Person
    sayName:function(){
         alert(this.name);
    }
};
var student1=new Student("evelyn","China");

特点:实例共享的属性和方法在原型中定义,除此之外的实例属性在构造函数中定义。

(五)动态原型模式

function Student(name,country){
    this.name=name;
    this.country=country;
    if(typeof this.sayName!="function"){
        Student.prototype.sayName=function(){
             alert(this.name);
        };
    }
};
var student1=new Student("evelyn","China");

(六)寄生构造函数模式

function Student(name,country){
    var o=new Object();
    o.name=name;
    o.country=country;
    o.sayName=function(){
        alert(this.name);
    };
    return o;
}
var student1=new Student("evelyn","China");

(七)稳妥构造函数模式

function Student(name,country){
    var o=new Object();
    o.sayName=function(){
        alert(name);
    };  //只能通过sayName方法访问name的值
    return o;
}
var student1=Student("evelyn","China");
上一篇下一篇

猜你喜欢

热点阅读