JavaScript Object-oriented

Source: Internet
Author: User

Object-oriented programming is an abstract way to create a programming pattern based on a real-world model. It uses previously established examples, including modularity, polymorphism, and encapsulation of several technologies. Today, many popular programming languages (such as java,javascript,c#,c+ +,python,php,ruby and OBJECTIVE-C) support object-oriented programming (OOP).

Object-oriented programming can be thought of as a software design that uses a series of objects to collaborate with one another, a program is simply a collection of functions, or a simple list of computer instructions, relative to conventional wisdom. In OOP, each object is able to receive messages, process data, and send messages to other objects. Each object can be thought of as a separate small machine with clear roles or responsibilities.

Object-oriented programming is designed to promote greater flexibility and maintainability in programming, and is popular in large-scale software engineering. With its emphasis on modularity, object-oriented code development is simpler and easier to understand, compared to non-modular programming Method 1, which can analyze, encode and understand complex situations and processes more directly.
JavaScript Object-Oriented programming

A namespace is a container that allows developers to bundle all features under a unique, application-specific name. In JavaScript, namespaces are just another object that contains methods, properties, and objects.

The idea behind creating a JavaScript namespace is simple: A global object is created, and all variables, methods, and functions become properties of that object. Using namespaces also minimizes the likelihood of application name collisions.

Let's create a global variable called MYAPP.

Global namespaces
var MyApp = MyApp | | {};

In the preceding code example, we first check that MyApp is already defined (whether in the same file or in another file). If so, then use the existing MyApp global object, otherwise create an empty object called MyApp to encapsulate methods, functions, variables, and objects.

var MyApp = MyApp | | {};
Myapp.commonmethod ={
Regexforname: "Walter",
Regexfornameb:function (name) {
alert (this.regexforname);
}
}
MYAPP.commonMethod.regExForNameB (); ====> "Walter";
Standard built-in objects

JavaScript has several objects, such as Math,object,array and string objects, that are included in its core. The following example shows how to use the Math object to obtain a random number using its random () method.
Standard built-in objects

JavaScript has several objects, such as Math,object,array and string objects, that are included in its core. The following example shows how to use the Math object to obtain a random number using its random () method.
Custom Objects
Class

function person () {}
Or
var person = function () {}

Example

function Person (firstname) {
This.lastname = FirstName
};
var person1 = new Person ("Gavin");
var person2 = new Person ("Walter");
alert (person1.lastname);
alert (person2.lastname);

Method (Object properties)

Methods are similar to properties, but different: one is a function and the other can be defined as a function. Calling a method is much like accessing a property, but the add () is likely to take a parameter after the method name. To define a method, you need to assign a function to the prototype property of the class; The name assigned to the function is used to call the object externally.

In the following example, we define the method SayHello () for the person class and call it.

function Person (firstName) {
This.firstname = FirstName;
}

Person.prototype.sayHello = function () {
Alert ("Hello, I ' m" + this.firstname);
};

var person1 = new Person ("Alice");
var person2 = new Person ("Bob");

Call the person SayHello method.
Person1.sayhello (); Alerts "Hello, I ' m Alice"
Person2.sayhello (); Alerts "Hello, I ' m Bob"

In JavaScript, a method is usually a normal function that is bound to an object, which means that the method can be called outside of its context. Consider the code in the following example:

function Person (firstName) {
This.firstname = FirstName;
}

Person.prototype.sayHello = function () {
Alert ("Hello, I ' m" + this.firstname);
};

var person1 = new Person ("Alice");
var person2 = new Person ("Bob");
var hellofunction = Person1.sayhello;

Person1.sayhello (); Alerts "Hello, I ' m Alice"
Person2.sayhello (); Alerts "Hello, I ' m Bob"
Hellofunction (); Alerts "Hello, I ' m undefined" (or fails
With a TypeError in strict mode)
Alert (hellofunction = = = Person1.sayhello); Alerts true
Alert (hellofunction = = = Person.prototype.sayHello); Alerts true
Hellofunction.call (Person1); Alerts "Hello, I ' m Alice"

As shown in the example above, all references to the SayHello function, including Person1, Person.prototype, and Hellofunction, all refer to the same function.

In the process of calling a function, the value of this depends on how we call the function. In general, we call the function through an expression Person1.sayhello (): The function that is called from the property of an object. At this point this is set to the object (that is, person1) where we get the function. This is why Person1.sayhello () used the name "Alice" and Person2.sayhello () used the name "Bob".

However, the value of this is different when we use different calling methods. When called from the variable hellofunction (), this is set to the global object (in the browser, window). Since the object (very likely) has no FirstName attribute, we get the result "Hello, I ' m undefined". (This is the result of loose mode, in strict mode the result will be different (this will produce an error). But in order to avoid confusion, we don't deal with the details here. In addition, we can use Function#call (or function#apply) to set the value of this explicitly, as in the last example at the end.


Inherited



The way to create a specialized version class for one or more classes is called Inheritance (JavaScript only supports single inheritance). A specialized version of a class is often called a subclass, and the other class is usually called the parent class. In JavaScript, inheritance is implemented by assigning an instance of a child class to a parent class and specialized subclasses. In modern browsers, you can use Object.create to implement inheritance.

JavaScript does not detect the Prototype.constructor of subclasses (see Object.prototype), so we have to declare it manually.

In the following example, we define the student class as a subclass of the person class. We then redefined the SayHello () method and added the Saygoodbye () method.



Defining the person constructor
function Person (firstName) {
This.firstname = FirstName;
}

Adding methods to Person.prototype
Person.prototype.walk = function () {
Alert ("I am walking!");
};
Person.prototype.sayHello = function () {
Alert ("Hello, I ' m" + this.firstname);
};

Defining the Student constructor
function Student (firstName, subject) {
Call the parent class constructor to ensure that (using Function#call) "This" is set correctly during the call
Person.call (this, firstName);

Initialize student class-specific properties
This.subject = subject;
};

Create a Student.prototype object that is inherited by Person.prototype.
Note: A common mistake is to use "new person ()" to establish student.prototype.
There are many mistakes in doing this, and the most important thing is that when we instantiate
Cannot give any firstname parameter to the person class
The correct location to call person is as follows, we call it from student
Student.prototype = Object.create (Person.prototype); See note below

Set the "constructor" property to point to student
Student.prototype.constructor = Student;

Replace the "SayHello" method
Student.prototype.sayHello = function () {
Alert ("Hello, I ' m" + This.firstname + "). I ' m studying "+ This.subject +". ");
};

Add the "Saygoodbye" method
Student.prototype.sayGoodBye = function () {
Alert ("goodbye!");
};

Test Example:
var student1 = new Student ("Janet", "Applied Physics");
Student1.sayhello (); "Hello, I ' m Janet." I ' m studying applied Physics. "
Student1.walk (); "I am walking!"
Student1.saygoodbye (); "Goodbye!"

Check that instanceof works correctly
Alert (student1 instanceof person); True
Alert (student1 instanceof Student); True





for "Student.prototype = Object.create (Person.prototype);" In this line, in an old JavaScript engine that does not support the Object.create method, you can use a "Polyfill" (aka "shim", view the article link), or use a function to get the same return value, as in the following:

function CreateObject (PROTO) {
function ctor () {}
Ctor.prototype = Proto;
return new ctor ();
}

Usage:
Student.prototype = CreateObject (Person.prototype);

For more information please refer to Object.create, which also has an old JavaScript engine compatibility scheme (SHIM).
Packaging

In the previous example, the student class does not need to know how the walk () method of the person class is implemented, but the method can still be used; The student class does not need to explicitly define this method unless we want to change it. This is called encapsulation, and for all methods that inherit from the parent class, simply define what you want to change in the subclass.
Abstract

Abstraction is a mechanism that allows you to simulate a common part of a work problem. This can be achieved through inheritance (materialization) or composition.
JavaScript is materialized through inheritance by allowing instances of the class to be combined by the property values of other objects.

The JavaScript Function class inherits from the object class (which is typically materialized). The Function.prototype property is an object instance (this is a typical combination).

var foo = function () {};
Alert (' foo is a function: ' + (foo instanceof function)); Alerts "Foo is a function:true"
Alert (' Foo.prototype is an object: ' + (Foo.prototype instanceof Object)); Alerts "Foo.prototype is an object:true"

Polymorphic

Just like all methods and properties defined inside a prototype property, different classes can define a method with the same name, and the method works in the same class. And this is only true when two classes are not parent-child (inheritance chain, one class is not inherited from other classes).
Attention

The object-oriented programming techniques presented in this article are not the only implementations, and the object-oriented implementation in JavaScript is very flexible.

Similarly, the techniques presented in this article do not use any language hacks, nor do they mimic the object theory of other languages.

There are other more advanced object-oriented technologies in JavaScript, but these are beyond the scope of this article.

Article Source: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript#The_ object_.28class_instance.29

Using Object.create to implement class-style inheritance
Https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/create


JavaScript Object-oriented

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.