关于程序员:设计模式原型模式

7次阅读

共计 548 个字符,预计需要花费 2 分钟才能阅读完成。

原型模式用于在创建对象时,通过共享某个对象原型的属性和办法,从而达到进步性能、升高内存占用、代码复用的成果。
示例一
function Person(name) {
this.name = name;

this.config = {

a: "1",
b: "2",

};

this.hello = function () {

console.info("hello");

};
}
如果须要通过以上代码创立 100 个实例,那么将须要创立 100 个 config、100 个 hello,而这两个货色在每个实例外面是齐全一样的。
因而咱们能够通过提取公共代码的形式进行油优化。

const config = {
a: “1”,
b: “2”,
};
const hello = function () {
console.info(“hello”);
};
function Person(name) {
this.name = name;

this.config = config;

this.hello = hello
}
这样的形式使得无论创立多少个 Person 对象都只须要创立一个 config、一个 hello。然而依然净化全局变量、config 被误批改、Person 和其余代码耦合大、不易于代码扩大保护等问题。
因而能够通过原型的形式进行优化。

function Person() {}
var p = new Person();

正文完
 0