Introduction to Object-Oriented JavaScript 转载自:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript
Introduction to Object-Oriented JavaScript
JavaScript is object-oriented to its core, with powerful, flexible OOP capabilities. This article starts with an Introduction to object-oriented programming, then reviews the JavaScript object model, and finally demonstrates concepts of object-oriented programming in JavaScript.
JavaScript review
If you don't feel confident about JavaScript concepts such as variables, types, functions, and scope you can read about those topics in A re-introduction to JavaScript. You can also consult the Core JavaScript 1.5 Guide.
Object-oriented programming
Object-oriented programming is a programming paradigm that uses abstraction to create models based on the real world. It uses several techniques from previously established paradigms, including modularity, polymorphism, and encapsulation. 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 may be seen as the design of software using a collection of cooperating objects, as opposed to a traditional view in which a program may be seen as a collection of functions, or simply as a list of instructions to the computer. In OOP, each object is capable of receiving messages, processing data, and sending messages to other objects. Each object can be viewed as an independent little machine with a distinct role or responsibility.
Object-oriented programming is intended to promote greater flexibility and maintainability in programming, and is widely popular in large-scale software engineering. By virtue of its strong emphasis on modularity, object oriented code is intended to be simpler to develop and easier to understand later on, lending itself to more direct analysis, coding, and understanding of complex situations and procedures than less modular programming methods.2
Terminology
- Namespace
- A container which allows developers to bundle all functionality under a unique, application-specific name.
- Class
- Defines the characteristics of the object.
- Object
- An Instance of a class.
- Property
- An object characteristic, such as color.
- Method
- An object capability, such as walk.
- Constructor
- A method called at the moment of instantiation.
- Inheritance
- A class can inherit characteristics from another class.
- Encapsulation
- A class defines only the characteristics of the object, a method defines only how the method executes.
- Abstraction
- The conjunction of complex inheritance, methods, properties of an object must be able to simulate a reality model.
- Polymorphism
- Poly means "many" and morphism means "forms". Different classes might define the same method or property.
For a more extensive description of object-oriented programming, see Object-oriented programming at Wikipedia.
Prototype-based programming
Prototype-based programming is a style of object-oriented programming in which classes are not present, and behavior reuse (known as inheritance in class-based languages) is accomplished through a process of decorating existing objects which serve as prototypes. This model is also known as class-less, prototype-oriented, or instance-based programming.
The original (and most canonical) example of a prototype-based language is the programming language Self developed by David Ungar and Randall Smith. However, the class-less programming style has recently grown increasingly popular, and has been adopted for programming languages such as JavaScript, Cecil, NewtonScript, Io, MOO, REBOL, Kevo, Squeak (when using the Viewer framework to manipulate Morphic components), and several others.2
JavaScript Object Oriented Programming
Namespace
A namespace is a container which allows developers to bundle up all functionality under a unique, application-specific name. In JavaScript a namespace is just an object containing methods, properties and objects. The Idea behind creating a namespace in JavaScript is simple: one global object is created and all variables, methods and functions become properties of that object. Use of namespaces also minimizes the possibility of name conflicts in an application.
An object is a Namespace:
Let's create a global object called MYAPP
// global namespace
var MYAPP = MYAPP || {};
Here in above code sample we have first checked whether MYAPP is already defined in same file or in another file If yes then use existing MYAPP global object otherwise create empty object called MYAPP which will encapsulate method, functions, variable and object.
We can also create sub namespace:
// sub namespace
MYAPP.event = {};
Below is code syntax for creating namespace and adding variable, function and method:
// Create container called MYAPP.commonMethod for common method and properties
MYAPP.commonMethod = {
regExForName: "", // define regex for name validation
regExForPhone: "", // define regex for phone no validation
validateName: function(name){
// Do something with name, you can access regExForName variable
// using "this.regExForName"
},
validatePhoneNo: function(phoneNo){
// do something with phone number
}
}
// Object together with the method declarations
MYAPP.event = {
addListener: function(el, type, fn) {
// code stuff
},
removeListener: function(el, type, fn) {
// code stuff
},
getEvent: function(e) {
// code stuff
}
// Can add another method and properties
}
//Syntax for Using addListner method:
MYAPP.event.addListener("yourel", "type", callback);
Core Objects
JavaScript has several objects included in its core, for example, there are objects like Math, Object, Array, and String. The example below shows how to use the Math object to get a random number by using its random()
method.
alert(Math.random());
alert
(such as the one included in web browsers) is defined globally. The alert
function is not actually a part of JavaScript itself.See Core JavaScript 1.5 Reference:Global Objects for a list of the core objects in JavaScript.
Every object in JavaScript is an instance of the object Object
and therefore inherits all its properties and methods.
Custom Objects
The Class
JavaScript is a prototype-based language which contains no class statement, such as is found in C++ or Java. This is sometimes confusing for programmers accustomed to languages with a class statement. Instead, JavaScript uses functions as classes. Defining a class is as easy as defining a function. In the example below we define a new class called Person.
function Person() { }
or
var Person = function(){ }
The Object (Class Instance)
To create a new instance of an object obj
we use the statement new obj
, assigning the result (which is of type obj
) to a variable to access it later.
In the example below we define a class named Person
and we create two instances (person1
and person2
).
function Person() { }
var person1 = new Person();
var person2 = new Person();
The Constructor
The constructor is called at the moment of instantiation (the moment when the object instance is created). The constructor is a method of the class. In JavaScript, the function serves as the constructor of the object therefore, there is no need to explicitly define a constructor method. Every action declared in the class gets executed at the time of instantiation.
The constructor is used to set the object's properties or to call methods to prepare the object for use. Adding class methods and their definitions occurs using a different syntax described later in this article.
In the example below, the constructor of the class Person
displays an alert when a Person
is instantiated.
function Person() {
alert('Person instantiated');
}
var person1 = new Person();
var person2 = new Person();
The Property (object attribute)
Properties are variables contained in the class; every instance of the object has those properties. Properties should be set in the prototype property of the class (function) so that inheritance works correctly.
Working with properties from within the class is done using the keyword this
, which refers to the current object. Accessing (reading or writing) a property outside of the class is done with the syntax: InstanceName.Property
; this is the same syntax used by C++, Java, and a number of other languages. (Inside the class the syntax this.Property
is used to get or set the property's value.)
In the example below we define the firstName
property for the Person
class and we define it at instantiation.
function Person(firstName) {
this.firstName = firstName;
alert('Person instantiated');
}
var person1 = new Person('Alice');
var person2 = new Person('Bob');
// Show the firstName properties of the objects
alert('person1 is ' + person1.firstName); // alerts "person1 is Alice"
alert('person2 is ' + person2.firstName); // alerts "person2 is Bob"
The Methods
Methods follow the same logic as properties; the difference is that they are functions and they are defined as functions. Calling a method is similar to accessing a property, but you add ()
at the end of the method name, possibly with arguments. To define a method, assign a function to a named property of the class's prototype
property; the name that the function is assigned to is the name that the method is called by on the object.
In the example below we define and use the method sayHello()
for the Person
class.
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 methods are regular function objects that are bound to an object as a property, which means they can be invoked "out of the context". Consider the following example code:
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 that example shows, all of the references we have to the sayHello
function — the one on person1
, on Person.prototype
, in the helloFunction
variable, etc. — refer to the same function. The value of this
during a call to the function depends on how we call it. In the common case when we call it in an expression where we got the function from an object property — person1.sayHello()
— this
is set to the object we got the function from (person1
), which is why person1.sayHello()
uses the name "Alice" and person2.sayHello()
uses the name "Bob". But if we call it other ways, this
is set differently: Calling it from a variable — helloFunction()
— sets this
to the global object (window
, on browsers). Since that object (probably) doesn't have a firstName
property, we end up with "Hello, I'm undefined". (That's in loose mode code; it would be different [an error] in strict mode, but to avoid confusion we won't go into detail here.) Or we can set this
explicitly using Function#call
(or Function#apply
), as shown at the end of the example.
Inheritance
Inheritance is a way to create a class as a specialized version of one or more classes (JavaScript only supports single inheritance). The specialized class is commonly called the child, and the other class is commonly called the parent. In JavaScript you do this by assigning an instance of the parent class to the child class, and then specializing it. In modern browsers you can also use Object.create to implement inheritance.
JavaScript does not detect the child class prototype.constructor
see Core JavaScript 1.5 Reference:Global Objects:Object:prototype property, so we must state that manually.
In the example below, we define the class Student
as a child class of Person
. Then we redefine the sayHello()
method and add the sayGoodBye()
method.
// Define the Person constructor
function Person(firstName) {
this.firstName = firstName;
}
// Add a couple of methods to Person.prototype
Person.prototype.walk = function(){
alert("I am walking!");
};
Person.prototype.sayHello = function(){
alert("Hello, I'm " + this.firstName);
};
// Define the Student constructor
function Student(firstName, subject) {
// Call the parent constructor, making sure (using Function#call) that "this" is
// set correctly during the call
Person.call(this, firstName);
// Initialize our Student-specific properties
this.subject = subject;
};
// Create a Student.prototype object that inherits from Person.prototype.
// Note: A common error here is to use "new Person()" to create the Student.prototype.
// That's incorrect for several reasons, not least that we don't have anything to
// give Person for the "firstName" argument. The correct place to call Person is
// above, where we call it from Student.
Student.prototype = Object.create(Person.prototype); // See note below
// Set the "constructor" property to refer 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 a "sayGoodBye" method
Student.prototype.sayGoodBye = function(){
alert("Goodbye!");
};
// Example usage:
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
Regarding the Student.prototype = Object.create(Person.prototype);
line: On older JavaScript engines without Object.create
, one can either use a "polyfill" (aka "shim", see the linked article), or one can use a function that achieves the same result, such as:
function createObject(proto) {
function ctor() { }
ctor.prototype = proto;
return new ctor();
}
// Usage:
Student.prototype = createObject(Person.prototype);
Encapsulation
In the previous example, Student
does not need to know how the Person
class's walk()
method is implemented, but still can use that method; theStudent
class doesn't need to explicitly define that method unless we want to change it. This is called encapsulation, by which every class inherits the methods of its parent and only needs to define things it wishes to change.
Abstraction
Abstraction is a mechanism that permits modeling the current part of the working problem. This can be achieved by inheritance (specialization), or composition. JavaScript achieves specialization by inheritance, and composition by letting instances of classes be the values of attributes of other objects.
The JavaScript Function class inherits from the Object class (this demonstrates specialization of the model). and the Function.prototype property is an instance of Object (this demonstrates composition)
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"
Polymorphism
Just like all methods and properties are defined inside the prototype property, different classes can define methods with the same name; methods are scoped to the class in which they're defined. This is only true when the two classes do not hold a parent-child relation (when one does not inherit from the other in a chain of inheritance).
Notes
The techniques presented in this article to implement object-oriented programming are not the only ones that can be used in JavaScript, which is very flexible in terms of how object-oriented programming can be performed.
Similarly, the techniques shown here do not use any language hacks, nor do they mimic other languages' object theory implementations.
There are other techniques that make even more advanced object-oriented programming in JavaScript, but those are beyond the scope of this introductory article.
References
- Mozilla. "Core JavaScript 1.5 Guide", https://developer.mozilla.org/docs/Web/JavaScript/Guide
- Wikipedia. "Object-oriented programming", http://en.wikipedia.org/wiki/Object-...ed_programming
- OOP JavaScript Overview series by Kyle Simpson
Document Tags and Contributors
Introduction to Object-Oriented JavaScript 转载自:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript的更多相关文章
- A re-introduction to JavaScript (JS Tutorial) 转载自:https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript
A re-introduction to JavaScript (JS Tutorial) Redirected from https://developer.mozilla.org/en-US/do ...
- https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError
- https://developer.mozilla.org/
Document/querySelector https://developer.mozilla.org/zh-CN/docs/Web/API/Document/querySelector
- 如何从https://developer.mozilla.org上查询对象的属性、方法、事件使用说明和示例
在https://developer.mozilla.org搜索要在前面加上指令 搜索之后点进去 进入之后就是这样的 在页面左边你可以选择自己要查询的对象 里面就是会有属性.方法.事件使用说明和示例.
- Object.create() __https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/create
Object.create() 方法会使用指定的原型对象及其属性去创建一个新的对象. 语法 Object.create(proto[, propertiesObject]) 参数 proto 新创建对 ...
- Object.keys() https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
Object.keys() 方法会返回一个由一个给定对象的自身可枚举属性组成的数组,数组中属性名的排列顺序和使用for...in 循环遍历该对象时返回的顺序一致 (两者的主要区别是 一个 for-in ...
- for ...in 、for each ...in、 for...of(https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/for...of)
1.for in for...in语句以任意顺序遍历一个对象的可枚举性.对于每个不同的属性,语句都会被执行. 语法 for (variable in object) {...} variable 在每 ...
- js对象 数组Array详解 (参照MDN官网:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find)
一:数组的创建方式: 1.采用直接量创建 var arr = [];//创建一个空数组 var arr2 = [1,2,3];//创建一个有三个元素的数组 2.采用构造函数创建 a.var arr1 ...
- 使用Camera API https://developer.mozilla.org/zh-CN/docs/Web/Guide/API/Camera
使用Camera API 在本文章中 获取到所拍摄照片的引用 在网页中展示图片 完整的示例代码 HTML页面: JavaScript文件: 浏览器兼容性 通过Camera API,你可以使用手机的摄像 ...
随机推荐
- 6层PCB设计技巧和步骤
6层PCB设计技巧和步骤 一.原理图的编辑 6层板由于PCB板中可以有两层地,所以可以将模拟地和数字地分开.对于统一地还是分开地,涉及到电磁干扰中信号的最小回流路径问题,绘制完原理图,别忘检查错误和 ...
- HDU4089/Uva1498 Activation 概率DP(好题)
题意:Tomato要在服务器上激活一个游戏,一开始服务器序列中有N个人,他排在第M位,每次服务器会对序列中第一位的玩家进行激活,有四种结果: 1.有p1的概率会激活失败,这时候序列的状态是不变的.2. ...
- java 一个数组的长度
package java03; /* *如何获取数组长度 : * 格式: * 数组名称.length * * 这会得到一个int数字,代表数组的长度 * * 数组一旦创建,程序运行期间,长度不可改变 ...
- RequestMappingHandlerMapping详解
我们先理简单梳理一个关系 关系梳理 spring ioc 是spring的核心,用来管理spring bean的生命周期 MVC 是一种使用 MVC(Model View Controller 模型- ...
- D3笔记01——D3简介与安装
1 D3简介 发布于2011年,全称Data-Driven Documents,直译为“数据驱动的文档”. 简单概括为一句话:D3是一个Javascript的函数库,是用来做数据可视化的.文档指DOM ...
- MySQL执行外部sql脚本文件命令报错:unknown command '\'
由于编码不一致导致的 虽然大部分导出是没有问题的 但是数据表中存储包含一些脚本(富文本内容)会出现该问题,强制指定编码即可解决. mysql导入时指定编码: mysql -u root -p --de ...
- python之chardet用来检测字符串编码的
import chardet a=b'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8c\xe4\xb8\x96\xe7\x95\x8c\xe3\x80\x82'print(ch ...
- 【Mybatis】Mybatis缓存
mybatis提供了缓存机制减轻数据库压力,提高数据库性能 mybatis的缓存分为两级:一级缓存.二级缓存 一级缓存是SqlSession级别的缓存,缓存的数据只在SqlSession内有效 二级缓 ...
- 4412 GPIO初始化
一.GPIO的初始化 • 在内核源码目录下使用命令“ls drivers/gpio/*.o”,可以看到“gpioexynos4”被编译进了内核.通过搜索*.o文件,可以知道内核编译内哪些文件.针对的看 ...
- Pangu and Stones HihoCoder - 1636 区间DP
Pangu and Stones HihoCoder - 1636 题意 给你\(n\)堆石子,每次只能合成\(x\)堆石子\((x\in[L, R])\),问把所有石子合成一堆的最小花费. 思路 和 ...