欢迎来到DIVCSS5查找CSS资料与学习DIV CSS布局技术!
您的位置:DIVCSS5首页 > HTML >

 

1、构造函数模式
[url=]file:///C:/Users/i037145/AppData/Local/Temp/msohtmlclip1/01/clip_image001.gif[/url]
function Person(name,age,job){
    this.name = name;
    this.age = age;
    this.job = job;
    this.sayName = function(){
        alert(this.name);
    };
}

varperson1 = new Person("Nicholas",29,"Software Engineer");
varperson2 = new Person("Greg",27,"Doctor");

person1.sayName();//"Nicholas"
person2.sayName();//"Greg"

alert(person1.constructor == Person);//true
alert(person2.constructor == Person);//true

alert(person1 instanceof Object);//true
alert(person1 instanceof Person);//true
alert(person2 instanceof Object);//true
alert(person2 instanceof Person);//true
[url=]file:///C:/Users/i037145/AppData/Local/Temp/msohtmlclip1/01/clip_image001.gif[/url]
问题:
每个方法都要在每个实例上重新创建一遍。在前面的例子中,person1person2都有一个名为sayName()的方法,但那两个方法不是同一个Function的实例。
alert(person1.sayName ==person2.sayName);//false
然而,创建两个完成同样任务的Function实例的确没有必要;况且有this对象在,根本不用在执行代码前就把函数绑定到特定对象上面。因此,可以通过把函数定义转移到构造函数外部来解决这个问题:
[url=]file:///C:/Users/i037145/AppData/Local/Temp/msohtmlclip1/01/clip_image001.gif[/url]
function Person(name,age,job){
    this.name = name;
    this.age = age;
    this.job = job;
    this.sayName = sayName;
}

functionsayName(){
    alert(this.name);
}

varperson1 = new Person("Nicholas",29,"Software Engineer");
varperson2 = new Person("Greg",27,"Doctor");

alert(person1.sayName == person2.sayName);//true
[url=]file:///C:/Users/i037145/AppData/Local/Temp/msohtmlclip1/01/clip_image001.gif[/url]
问题:在全局作用域中定义的函数实际上只能被某个对象调用,这让全局作用域有点名不副实。更让人无法接受的是:如果对象需要定义很多方法,那么就要定义很多个全局函数,于是我们这个自定义的引用类型就丝毫没有封装性可言了。
2
、原型模式
3
、组合使用构造函数模式和原型模式
4
、原型链
5
、组合继承
6
、原型式继承
7
、寄生式继承
8
、寄生组合式继承
9
、拷贝组合式继承

 

如需转载,请注明文章出处和来源网址:http://www.divcss5.com/html/h19289.shtml

如对文章有任何疑问请提交到DIV CSS论坛,或有任何网页制作CSS问题立即到CSS论坛发贴求解 或 直接DIVCSS5网页顶部搜索遇到DIVCSS疑问。
CSS教程文章修订日期:2018-08-14 17:37 原创:DIVCSS5
本文www.divcss5.com DIVCSS5版权所有。