原型模式用于在创建对象时,通过共享某个对象原型的属性和方法,从而达到提高性能、降低内存占用、代码复用的效果。
示例一
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();


e4lqc281
1 声望0 粉丝