Home > Web Front-end > JS Tutorial > Detailed explanation of javascript prototype pattern usage examples_javascript skills

Detailed explanation of javascript prototype pattern usage examples_javascript skills

WBOY
Release: 2016-05-16 15:56:38
Original
1225 people have browsed it

The examples in this article describe the usage of JavaScript prototype mode. Share it with everyone for your reference. The specific analysis is as follows:

Generally after understanding the disadvantages of factory pattern and constructor pattern, you will know why prototype pattern is needed

Definition of prototype pattern i: Every function has a prototype attribute, which is an object whose purpose is to contain properties and methods that can be shared by all instances of a specific type. For example, in the sayInformation() method in the constructor model, if two instances are declared, the sayInformation method must be constructed twice, but it is not necessary to declare it twice. This is why the prototype pattern appears (Nima, those blogs on the Internet all have Is it nonsense, or is it easy to understand when reading a book), after sayInformation() is declared as prototype mode, the instance is shared, and there is no need to declare it twice

function Person(){}
Person.prototype.name="jack";
Person.prototype.age=10;
Person.prototype.sayInformation=function()
{
  console.log("my name is"+this.name+" age is"+this.age);
}
var person1 = new Person();
person1.sayInformation();
console.info(person1.name);
//来自原型的属性name
person1.name="Greg";
//修改实例的name属性
console.info(person1.name);
//来自实例的属性name
delete person1.name ;
//来自实例的属性,这里删除的是实例的属性,但是原型的属性依然存在
console.info(person1.name);
//来自原型的属性name
var person2 = new Person();
person2.sayInformation();
console.info(person1.hasOwnProperty("name"));
//hasOwnProperty检查属性是属于实例还是原型中,如果是实例中就返回true
console.info(person1.name==person2.name);
console.info(person1.sayInformation==person2.sayInformation);
console.info(person1.constructor);
//指向person1的构造函数
//原型更加简便的写法
function Person2(){}
Person2.prototype={
  name:"jack",
  age:29,
  sayInformationfunction:function()
    {
      console.log("my name is"+this.name+" age is"+this.age);
    }
}
Copy after login

I hope this article will be helpful to everyone’s JavaScript programming design.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template