常用的前端开发设计模式有哪些


本文摘自PHP中文网,作者清浅,侵删。

前端开发设计模式有:1、模块模式;2、构造函数模式;3、工厂模式;4、混合模;5、单例模式;6、订阅发布模式等等。

常用的前端开发设计模式有:模块模式,构造函数模式,工厂模式,混合模式,单例模式以及订阅-发布模式。

前端开发设计模式

模块模式:

在立即执行函数表达式中定义的变量和方法在外界是访问不到的,只能通过其向外部提供的接口,"有限制"地访问.通过函数作用域解决了属性和方法的封装问题.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

var Person = (function(){   

var name = "xin";   

var age = 22;   

function getName(){       

return name;

    }   

function getAge(){       

return age;

    }   

return {       

getName: getName,       

getAge: getAge

    }

})();

console.log(age); // 报错:age未定义

console.log(name); // 报错:name未定义

console.log(Person.age); // undefined

console.log(Person.name); // undefined只能通过Person提供的接口访问相应的变量

console.log(Person.getName()); // xin

console.log(Person.getAge()); // 22

构造函数模式

1

2

3

4

5

6

7

8

9

10

11

12

13

14

function Person(name,age){   

this.name = name;   

this.age = age;

}

Person.prototype = {   

constructor: Person;

    printName: function(){       

console.log(this.name);

    },    printAge: function(){       

console.log(this.age);

    }

}var person = new Person('xin', 22);

person.printName(); // xin

person.printAge(); // 22

混合模式

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

function Person(name,age){   

this.name = name;   

this.age = age;

};

Person.prototype.printName = function(){   

console.log(this.name);

}function Student(name,age){

    //继承 Person 的属性

    Person.call(this,name,age);

}function create(prototype){   

function F(){};

    F.prototype = prototype;   

    return new F();

}

//让Student的原型指向一个对象,该对象的原型指向了Person.prototype,通过这种方式继承 Person 的方法

Student.prototype = create(Person.prototype);

Student.prototype.printAge = function(){   

console.log(this.age);

}var student = new Student('xin',22);

student.printName(); // "xin"

工厂模式

1

2

3

4

5

6

7

8

9

10

11

12

13

function Person(name, age){   

var person = new Object();

    person.name = name;

    person.age = age;

    person.printName = function(){       

    console.log(this.name);

    };

    person.printAge = function(){       

    console.log(this.age);

    }   

    return person;

}

var person = Person('xin',22);

单例模式

1

2

3

4

5

6

7

8

9

10

11

12

13

var Singleton = (function (){   

var instance;   

function init(){       

return {

        };

    }    return {       

    getInstance: function(){           

    if(!instance){

               instace = init();

            }            return instance;

        }

    };

})();

发布-订阅模式

阅读剩余部分

相关阅读 >>

前端开发是做什么的

什么是前端开发和后端开发?前端开发和后端开发哪个好

常用的前端开发设计模式有哪些

前端开发代码注释的作用及使用示范

前端开发需要学什么?前端需要掌握的技术

web前端开发和后端开发的区别是什么

前端开发需要掌握什么技术

20个为前端开发者准备的文档和指南(2)

学习web前端开发的需要哪些条件

20个为前端开发者准备的文档和指南(3)

更多相关阅读请进入《前端开发》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...