Home Web Front-end JS Tutorial Introduction to JavaScript Design Patterns and Prototype Patterns (Object.create and prototype)_javascript skills

Introduction to JavaScript Design Patterns and Prototype Patterns (Object.create and prototype)_javascript skills

May 16, 2016 pm 04:23 PM
javascript object.create Prototype pattern Design Patterns

Prototype Mode Description

Description: Use prototype instances to copy and create new customizable objects; for new objects, you do not need to know the specific process of creating the original object;

Process: Prototype => new ProtoExam => clone to new Object;

Use relevant code:

Copy code The code is as follows:

function Prototype() {
This.name = '';
This.age = '';
This.sex = '';
}

Prototype.prototype.userInfo = function() {
Return 'Personal information, name: ' this.name ', age: ' this.age ', gender: ' this.sex '
';
}

Two or more personal information contents are now required:


Copy code The code is as follows:

var proto = new Prototype();
var person1 = Object.create(proto);
person1.name = 'Xiao Ming';
person1.sex = 'Male';
person1.age = 35;
person1.userInfo();
//
var person2 = Object.create(proto);
person2.name = 'Xiaohua';
person2.sex = 'Female';
person2.age = 33;
person2.userInfo();

Output return:


Copy code The code is as follows:

Personal information, Name: Xiao Ming, Age: 35, Gender: Male
Personal information, Name: Xiaohua, Age: 33, Gender: Female


Prototype mode is generally used when the abstract structure is complex, but the content composition is similar, the abstract content can be customized, and the newly created object only needs to be slightly modified to meet the requirements;

Object.create Instructions

1>. Definition: Create an object that can specify a prototype object and can contain optional custom properties;
2> Object.create(proto [, properties]); Optional, used to configure the properties of the new object;

Copy code The code is as follows:

1. proto: To create a prototype of a new object, it is required and can be null; this proto is only valuable if it has already been created [new] or object.prototype;
2. properties: optional, structure:
{
​​ propField: {
              value: 'val'|{}|function(){},
writable: true|false,
enumerable: true|false,
Configurable: true|false,
              get:function(){return 10},
             set:function(value){}
}
}
Custom attributes have the following four native attributes:
value: custom attribute value;
writable: Whether the value of this item is editable, the default is false, when it is true, obj.prodField can be assigned a value; otherwise it is read-only;
enumerable: enumerable;
confirurable: configurable;

Can also contain set, get accessor methods;

Among them, [set, get] and value and writable cannot appear at the same time;

1. Create prototype object class:

Copy code The code is as follows:

function ProtoClass(){
This.a = 'ProtoClass';
This.c = {};
This.b = function() {
}
}

Create prototype method:
Copy code The code is as follows:

ProtoClass.prototype.aMethod = function() {
//this.a;
//this.b();
Return this.a;
}

How to use

1. Create an object with ProtoClass.prototype;

Copy code The code is as follows:

var obj1 = Object.create(ProtoClass.prototype, {
foo:{value: 'obj1', writable: true}
})

obj1 has the ProtoClass prototype method aMethod;
Copy code The code is as follows:

obj1.aMethod();
//It will output undefined, the method is accessible, and the ProtoClass members are inaccessible

However, this method cannot implement the member attributes of a, b, c under ProtoClass:

2. Use instantiated ProtoClass as prototype:

Copy code The code is as follows:

var proto = new ProtoClass();

var obj2 = Object.create(proto, {
foo:{value:'obj2'}
});


The obj2 created in this way has all the member attributes a, b, c and aMethod prototype method of ProtoClass; and adds a foo read-only data attribute;
Copy code The code is as follows:

obj2.a; //ProtoClass
obj2.c: //[Object]
obj2.b(); //

obj2.aMethod(); //ProtoClass
obj2.foo; //obj2

3. Subclass inheritance:

Copy code The code is as follows:

function SubClass() {
 
}
SubClass.prototype = Object.create(ProtoClass.prototype ,{
foo:{value: 'subclass'}
});

SubClass.prototype.subMethod = function() {
Return this.a || this.foo;
}

This method can be inherited to the aMethod method of ProtoClass and executed;

Copy code The code is as follows:

var func = new SubClass();
func.aMethod() ;//undefined, cannot read the member attributes of ProtoClass, a, b, c
func.subMethod();//subclass

To allow SubClass to read the member attributes of ProtoClass, SubClass needs to be changed:

Copy code The code is as follows:

function SubClass()
{
ProtoClass.call(this);
}

//Other codes;

This method can obtain the member attributes and prototype methods of ProtoClass;:

Copy code The code is as follows:

var func = new SubClass();
func.aMethod() ;//ProtoClass
func.subMethod();//ProtoClass

Another method is to use an instantiated ProtoClass object as the prototype of SubClass;

Copy code The code is as follows:

var proto = new ProtoClass();

function SubClass() {
}

SubClass.prototype = Object.create(proto, {
foo:{value: 'subclass'}
});

In this way, after SubClass is instantiated, you can obtain all the properties and prototype methods of ProtoClass, and create a read-only data attribute foo;

Copy code The code is as follows:

var func = new SubClass();
func.foo; //subclass
func.a; //ProtoClass
func.b(); //
func.c; //[Object]
func.aMethod(); //ProtoClass

4. Another creation inheritance method has the same effect as Object.create using instantiated ProtoClass as prototype:

Copy code The code is as follows:

function SubClass() {
​this.foo = 'subclass'; //But it can be read and written here
}

SubClass.prototype = new ProtoClass();

Object.create related instructions

Object.create is used to create a new object. When it is Object, the prototype is null, and the function is the same as new Object(); or {};

When it is a function, it has the same effect as new FunctionName;

Copy code The code is as follows:

//1 Object
var o = {}
//Equivalent to
var o2 = Object.create({});
//Both constructors are the same;

//----------------------------------------
function func() {
This.a = 'func';
}
func.prototype.method = function() {
Return this.a;
}

var newfunc = new func();
//Equivalent to [same effect]
var newfunc2 = Object.create(Object.prototype/*Function.prototype||function(){}*/, {
a: {value:'func', writable:true},
Method: {value: function() {return this.a;} }
});

But newfunc and newfunc2 have different function references in the objects that create them.

newfunc is function func() {...}, newfunc2 is function Function {Native}

Copy code The code is as follows:

Object.create(proto[, propertiesField]):

proto description, this value is required and can be null. If not set, an exception will be thrown;

If proto is non-null, it is an instantiated value, that is, a value that has been new; most objects in JavaScript have a constructor attribute, which indicates which function this object is instantiated through;

propertiesField is optional and sets the member properties or methods that the newly created object may need;

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The difference between design patterns and architectural patterns in Java framework The difference between design patterns and architectural patterns in Java framework Jun 02, 2024 pm 12:59 PM

In the Java framework, the difference between design patterns and architectural patterns is that design patterns define abstract solutions to common problems in software design, focusing on the interaction between classes and objects, such as factory patterns. Architectural patterns define the relationship between system structures and modules, focusing on the organization and interaction of system components, such as layered architecture.

The wonderful use of the adapter pattern in Java design patterns The wonderful use of the adapter pattern in Java design patterns May 09, 2024 pm 12:54 PM

The Adapter pattern is a structural design pattern that allows incompatible objects to work together. It converts one interface into another so that the objects can interact smoothly. The object adapter implements the adapter pattern by creating an adapter object containing the adapted object and implementing the target interface. In a practical case, through the adapter mode, the client (such as MediaPlayer) can play advanced format media (such as VLC), although it itself only supports ordinary media formats (such as MP3).

Analysis of the Decorator Pattern in Java Design Patterns Analysis of the Decorator Pattern in Java Design Patterns May 09, 2024 pm 03:12 PM

The decorator pattern is a structural design pattern that allows dynamic addition of object functionality without modifying the original class. It is implemented through the collaboration of abstract components, concrete components, abstract decorators and concrete decorators, and can flexibly expand class functions to meet changing needs. In this example, milk and mocha decorators are added to Espresso for a total price of $2.29, demonstrating the power of the decorator pattern in dynamically modifying the behavior of objects.

PHP design pattern practical case analysis PHP design pattern practical case analysis May 08, 2024 am 08:09 AM

1. Factory pattern: Separate object creation and business logic, and create objects of specified types through factory classes. 2. Observer pattern: allows subject objects to notify observer objects of their state changes, achieving loose coupling and observer pattern.

How design patterns deal with code maintenance challenges How design patterns deal with code maintenance challenges May 09, 2024 pm 12:45 PM

Design patterns solve code maintenance challenges by providing reusable and extensible solutions: Observer Pattern: Allows objects to subscribe to events and receive notifications when they occur. Factory Pattern: Provides a centralized way to create objects without relying on concrete classes. Singleton pattern: ensures that a class has only one instance, which is used to create globally accessible objects.

What are the advantages and disadvantages of using design patterns in java framework? What are the advantages and disadvantages of using design patterns in java framework? Jun 01, 2024 pm 02:13 PM

The advantages of using design patterns in Java frameworks include: enhanced code readability, maintainability, and scalability. Disadvantages include complexity, performance overhead, and steep learning curve due to overuse. Practical case: Proxy mode is used to lazy load objects. Use design patterns wisely to take advantage of their advantages and minimize their disadvantages.

Application of design patterns in Guice framework Application of design patterns in Guice framework Jun 02, 2024 pm 10:49 PM

The Guice framework applies a number of design patterns, including: Singleton pattern: ensuring that a class has only one instance through the @Singleton annotation. Factory method pattern: Create a factory method through the @Provides annotation and obtain the object instance during dependency injection. Strategy mode: Encapsulate the algorithm into different strategy classes and specify the specific strategy through the @Named annotation.

PHP Design Patterns: Test Driven Development in Practice PHP Design Patterns: Test Driven Development in Practice Jun 03, 2024 pm 02:14 PM

TDD is used to write high-quality PHP code. The steps include: writing test cases, describing the expected functionality and making them fail. Write code so that only the test cases pass without excessive optimization or detailed design. After the test cases pass, optimize and refactor the code to improve readability, maintainability, and scalability.

See all articles