Prototype Pattern(原型模式)

原型模式(Prototype Pattern):是指原型实例指向创建对象的种类,并通过拷贝这些原型创建新的对象,是一种用来创建对象的模式,也就是创建一个对象作为另一个对象的prototype属性。这种类型的设计模式属于创建型模式
在js中原型设计模式的使用要比java、C中要简单的多。

1、Object.create()

1、定义: 创建一个可指定原型对象的并可以包含可选自定义属性的对象;
2、 Object.create(proto [, properties]); 可选,用于配置新对象的属性;

方法说明
1. proto: 要创建新对象的 原型,必须,可为 null; 这个 proto 要是已经创建的[new过],或 对象.prototype 才有价值;

2. properties: 可选,结构为:

{

     propField: {

           value: 'val'|{}|function(){},

           writable: true|false,

           enumerable: true|false,

           configurable: true|false,

           get:function(){return 10},

           set:function(value){}

     }

}

自定的属性有以下的四种本置属性:

value: 自定义属性值;

writable: 该项值是否可编辑,默认为 false, 当为 true 时,obj.prodField 可赋值;否则只读;

enumerable: 可枚举; 

confirurable: 可配置;
还可以包含 set, get 访问器方法;
其中,[set, get] 与 value 和 writable 不能同时出现;

示例
* 原型模式使用
 * Object.create
 * **/
const person = {
  isHuman: false,
  printIntroduction: function() {
    console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
  }
};

const me = Object.create(person);

me.name = 'Matthew'; // "name" is a property set on "me", but not on "person"
me.isHuman = true; // inherited properties can be overwritten

me.printIntroduction();
// expected output: "My name is Matthew. Am I human? true"

2、prototype 来创建对象变量

/***
 * 使用prototype来创建实例对象
 * @param name
 * @returns {createPerson.Person}
 */
function createPerson(name){
  function  Person(){
};
 
  Person.prototype = person;
  let newPerson = new Person();
  newPerson.name = name;
  return newPerson;
}


let me = createPerson("Matthew");
me.isHuman = true;

me.printIntroduction();
// expected output: "My name is Matthew. Am I human? true"

java版类图

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容