面向对象(Object Oriented,缩写OO)有类的概念,通过类创立任意多个具备雷同属性和办法的对象。典型的面向对象语言(C++/Java),都有 "类"(class)这个概念。但JavaScript语言没有类的概念,而ECMAScript(简称ES)是基于原型实现的面向对象编程。
了解对象
对象是一组无序属性的汇合,一个属性就是一个键值对{"key:value"}。当初,咱们来简略的创立一个 Object
的实例。
var s1 = new Object();s1.name = "小赵";s1.age = 20;s1.sid = 2002;s1.sayHi = function() { console.log("Hi, My name is " + this.name);}
还能够应用对象字面量的语法创建对象。
var s1 = { name: "小赵", age: 20, sid: 2002, sayHi: function () { console.log("Hi, My name is " + this.name); }};
这样创立的实例对象与后面的一样。
属性类型
ES
中有数据属性和拜访器属性。
数据属性蕴含一个数据值的地位。在这个地位能够读取和写入值。
拜访器属性不蕴含数据值,而是应用getter
函数读取值,setter
函数写入值。
这两种属性都有4个形容其行为的个性。
属性个性
以下个性是属于数据属性:
[[Writable]]
:示意属性值是否被批改。默认为true
。[[Value]]
:示意属性的数据值。从这个地位能够读取属性值;也能够保留新的属性值。默认为undefined
。
以下个性是属于拜访器属性:
[[Get]]
:调用函数获取属性值。默认为undefined
。[[Set]]
:调用函数写入属性值。默认为undefined
。
而这两种属性类型都具备以下个性:
[[Configurable]]
:示意属性是否可配置。如通过delete
删除并从新定义属性,是否批改属性个性,是否将属性批改为拜访器属性(或者将属性批改为数据属性)。默认为true
。[[Enumerable]]
:示意是否通过for-in
循环遍历。默认为true
。设置为false
时,会使for-in
循环、Object.keys()
操作等跳过该属性。
Object.defineProperty
无论是数据属性批改属性默认的个性,还是拜访器属性的定义,都要应用ES5
的Object.defineProperty()
办法。该办法接管三个参数:要定义属性的对象,对象中要定义或批改的属性名和属性描述符。上面对数据属性进行定义。
var student ={};Object.defineProperty(student, "name", { writable: false, value: "小赵"});student.name; // 小赵student.name = "小钱";student.name; // 小赵
创立一个只读的 name
属性,它的值不可批改,非严格模式下批改值的操作会被疏忽;严格模式下会抛出谬误 。
相似的规定也实用于不可配置的属性。例如:
var student ={};Object.defineProperty(student, "name", { configurable: false, value: "小赵"});student.name; // 小赵delete student.name;student.name; // 小赵
configurable
的设置使得name
属性不能删除。在非严格模式下调用delete
会疏忽该操作,而严格模式下会报错。
而一旦设置为不可配置,就不能改回可配置了。此时,调用 Object.defineProperty()
办法批改除writable
之外的个性,都会导致谬误:
var student ={};Object.defineProperty(student, "name", { configurable: false, value: "小赵"});// TypeError: Cannot redefine property: nameObject.defineProperty(student, "name", { configurable: true, value: "小赵"});
能够屡次调用 Object.defineProperty()
办法批改同一个属性,但把 configurable
设置为 false
后,就会有限度。
在调用 Object.defineProperty()
办法时,如果不指定,configurable
、enumerable
和 writable
个性的默认值都是 false
,少数状况下,可能都没有必要利用 Object.defineProperty()
办法提供的这些高级性能。
而拜访器属性不能间接定义getter
与setter
,必须应用Object.defineProperty()
来定义。
var book = { _year: 2004, edition: 1};Object.defineProperty(book, "year", { get: function () { return this._year; }, set: function (newValue) { if (newValue > 2004) { this._year = newValue; this.edition += newValue - 2004; } }});book.year = 2006;console.log(book.edition); // 3
不肯定同时指定getter
和setter
。只指定getter
意味着可读不可写,写入属性时会疏忽,严格模式下会抛出谬误。相似的,只指定setter
意味着可写不可读,读取时返回undefined
,严格模式下会抛出谬误。
定义多个属性
当为对象定义多个属性时,能够应用ES5
定义的Object.defineProperties()
办法。这个办法接管两个对象参数:第一个对象是要增加和批改其属性的对象,第二个对象的属性与第一个对象中要增加或批改的属性一一对应。例如:
let book = {};Object.defineProperties(book, { _year: { value: 2004, writable: true }, edition: { value: 1, writable: true }, year: { get: function () { return this._year; }, set: function (newValue) { if (newValue > 2004) { this._year = newValue; this.edition += newValue - 2004; } } }});
定义了两个数据属性和一个拜访器属性。最终对象与下面定义的雷同。惟一区别是在这里的属性是同一时间创立的。
读取属性的个性
ES5
中的Object.getOwnPropertyDescriptor()
办法能够获得给定属性的描述符。这个办法接管两个参数:属性所在的对象和读取其描述符的属性名称。返回值是一个对象,如果是拜访器属性,这个对象的属性有configurable
、enumerable
、get
和set
;如果是数据属性,这个对象的属性有configurable
、enumerable
、writable
和value
。例如:
var book = {};Object.defineProperties(book, { _year: { value: 2004, writable: true }, edition: { value: 1, writable: true }, year: { get: function () { return this._year; }, set: function (newValue) { if (newValue > 2004) { this._year = newValue; this.edition += newValue - 2004; } } }});var descriptor = Object.getOwnPropertyDescriptor(book, "_year");console.log(descriptor.value); // 2004console.log(descriptor.configurable); // falseconsole.log(typeof descriptor.get); // undefinedvar descriptor = Object.getOwnPropertyDescriptor(book, "year");console.log(descriptor.value); // undefinedconsole.log(descriptor.enumerable); // falseconsole.log(descriptor.get); // [Function: get]
在JavaScript中,能够针对任何对象——包含DOM
和BOM
对象,应用Object.getOwnPropertyDescriptor()
办法。
创建对象
为了解决Object
构造函数或对象字面量创建对象产生的大量反复代码,开始应用工厂模式实现对象创立。
工厂模式
工厂模式形象创立具体对象的过程,因为ES6
之前无奈创立类,因而应用函数封装特定接口创建对象的细节。
function createStudent(name, age, sid) { var o = new Object(); o.name = name; o.age = age; o.sid = sid; o.sayHi = function () { console.log("Hi, My name is " + o.name); }; return o;}var s1 = createStudent("小周", 30, 2005);var s2 = createStudent("小吴", 18, 2006);
函数createStudent()
依据接管的参数构建Student
对象。该函数能够无数次调用,但没有解决对象辨认问题。
构造函数模式
ES
中构造函数用来创立特定类型的对象,自定义对象类型的属性和办法。
function Student(name, age, sid) { this.name = name; this.age = age; this.sid = sid; this.sayHi = function () { console.log("Hi, My name is " + this.name); };}var s1 = new Student("小郑", 45, 2008);var s2 = new Student("小王", 32, 2009);
在构造函数模式中,没有显示地创建对象,间接将属性和办法赋给this
对象,没有应用return
语句返回对象,能够应用new
调用这个构造函数。
此外,构造函数自身是函数,因而结尾大写与其它函数辨别。
实例对象中constructor
属性指向以后对象类型。
s1.constructor == Student; // trues2.constructor == Student; // true
也能够应用instanceof
查看对象类型。
s1 instanceof Object // trues1 instanceof Student // true
构造函数也是函数,能够不通过new
操作符调用,这样和其它函数就没什么区别。
// 当作构造函数应用var s1 = new Student("小冯", 37, 2010);s1.sayHi();// 作为一般函数调用Student("小新", 52, 2012);window.sayHi();// 在另一个对象的作用域中调用var o = new Object();Student.call(o, "小明", 66, 2020);o.sayHi();
构造方法中的每个办法都要在每个实例上创立一遍。就像下面例子中sayHi
办法的function() {}
创立与new Function()
是等价的。因而,不同实力上的同名函数是不相等的。
console.log(s1.sayHi == s2.sayHi); // false
因而,咱们能够将函数定义转移到构造函数的里面来解决。
function Student(name, age, sid) { this.name = name; this.age = age; this.sid = sid; this.sayHi = sayHi;}function sayHi() { console.log("HI, My name is " + this.name);}var s1 = new Student("小龙", 29, 2011);var s2 = new Student("小凤", 41, 2012);
但这样定义的函数要有很多时,咱们就须要定义多个全局函数,没有封装性可言。上面介绍一下原型模式,通过该模式来解决这种缺点。
原型模式
创立的每个函数都有一个prototype
属性,该属性指向一个对象,而对象是由特定类型的所有实例共享的属性和办法。这样能够将信息间接增加到原型对象中。
function Student() {}Student.prototype.name = "小圆";Student.prototype.age = 24;Student.prototype.sid = 2015;Student.prototype.sayHi = function() { console.log("Hi, My name is " + this.name);}var s1 = new Student();var s2 = new Student();
将所有属性和办法增加到原型对象上,对象上的属性和办法由所有实例共享。
了解原型对象
只有创立一个新函数,函数就会创立一个prototype
属性并指向函数的原型对象。默认状况下的所有原型对象都会主动取得constructor
属性,该属性蕴含指向prototype
属性所在函数的指针。而其它办法从Object
继承而来。当调用构造函数创立一个新实例后,该实例的外部将蕴含一个指针[[Prototype]]
来指向原型对象。
能够通过isPrototypeOf()
办法确定对象之间是否存在这种关系。从实质上讲,如果[[Prototype]]
指向调用isPrototypeOf
办法的对象Student.prototype
,那么这个办法就返回true
。
Student.prototype.isPrototypeOf(s1); // true
ES5
中减少了Object.getPrototypeOf()
办法,该办法返回对象的原型[[Prototype]]
。这种形式能够获取原型对象中的属性。
Object.getPrototypeOf(s1) == Student.prototype; // trueObject.getPrototypeOf(s1).name; // 小赵
代码在读取某个对象的属性时,都会从对象实例开始搜寻,如果没有找到,则再次搜寻指针指向的原型对象,这会执行两次搜寻,是多个实例共享原型属性和办法的原理。
原型最后只蕴含constructor
属性并且是共享的,能够通过对象实例拜访,但不能通过对象实例重写原型中的值。在实例中增加属性时,会屏蔽原型对象中的同名属性,不批改原型对象中的属性值。
function Student() {}Student.prototype.name = "小圆";Student.prototype.age = 24;Student.prototype.sid = 2015;Student.prototype.info = function() { console.log(this.name);}var s1 = new Student();var s2 = new Student();s1.name = "小诸";console.log(s1.name); // 小诸console.log(s2.name); // 小圆
能够应用delete
操作符能够删除实例对象中的属性,从而从新拜访原型中的属性。
delete s1.name;console.log(s1.name); // 小圆
应用hasOwnProperty()
办法检测一个属性是存在于实例中还是存在于原型中。该办法从Object
继承,只在给定属性存在于对象实例时,返回true
。
function Student() {}Student.prototype.name = "小圆";Student.prototype.age = 24;Student.prototype.sid = 2015;Student.prototype.info = function() { console.log(this.name);}var s1 = new Student();var s2 = new Student();s1.name = "小诸";s1.hasOwnProperty("name"); // true s1的name属性来自于实例s2.hasOwnProperty("name"); // false s2的name属性来自于原型
in
操作符能够断定属性是否在给定实例中,不论该属性是存在于实例中,还是原型中。
s1.hasOwnProperty("name"); // true s1的name属性来自于实例console.log("name" in s1); // trues2.hasOwnProperty("name"); // false s2的name属性来自于原型console.log("name" in s2); // true
这样的话,能够联合hasOwnProperty()
与in
来断定属性是否存在于实例还是原型中。
function hasPrototypeProperty(object, name) { return !object.hasOwnProperty(name) && (name in object);}
应用for-in
循环时,返回的是所有可通过对象拜访、可枚举的属性。而屏蔽了原型中不可枚举属性的实例属性也会在for-in
循环中(依据规定,开发人员定义的属性都是可枚举的)。
ES5
还提供Object.keys()
来获取对象中所有可枚举的实例对象。
var keys = Object.keys(Student.prototype);console.log(keys); // [ 'name', 'age', 'sid', 'info' ]var s1 = new Student4();s1.name = "小玲";s1.age = 18;var s1keys = Object.keys(s1);console.log(s1keys); // [ 'name', 'age' ]
Object.keys
传递原型,则获取是原型中所有属性,传递实例,则获取的是实例中所有属性。
还能够应用 Object.getOwnPropertyNames()
办法获取带有constructor
属性的实例的所有属性。
var keys = Object.getOwnPropertyNames(Student.prototype);console.log(keys); // [ 'constructor', 'name', 'age', 'sid', 'sayHi' ]
Object.keys()
和 Object.getOwnPropertyNames()
都能够代替 for-in
循环。
更简略的原型语法
以对象字面量模式创建对象重写原型对象的创立,缩小不必要的语法。
function Student() {}Student.prototype = { name: "小刘", age: 36, sid: 2016, sayHi: function () { console.log("Hi, My name is " + this.name); }};
这种以对象字面量模式创立新对象并指向Student.prototype
会导致constructor
属性不再指向Student
。因为这种语法在实质上齐全从新了默认的prototype
对象,因而constructor
属性会指向默认的Object
构造函数。
var s1 = new Student();console.log(s1 instanceof Object); // trueconsole.log(s1 instanceof Student); // trueconsole.log(s1.constructor == Student); // falseconsole.log(s1.constructor == Object); // true
如果须要constructor
属性,能够手动设置该属性的值。
function Student() {}Student.prototype = { constructor: Student, name: "小刘", age: 36, sid: 2016, sayHi: function () { console.log("Hi, My name is " + this.name); }};
但这种重设constructor
属性的形式会导致它变为可枚举的。默认是不可枚举的。能够通过ES5
的Object.defineProperty()
设置。
// 重设构造函数,只实用于ECMAScript5兼容的浏览器Object.defineProperty(Student.prototype, "constructor", { enumerable: false, value: Student});
原型的动态性
在原型中查找值的过程是一次搜寻,即使咱们先创立实例,再批改原型,都会反映到实例上。
var s1 = new Student();Student.prototype.sayHi = function() { console.log("Hi");}s1.sayHi(); // Hi
调用构造函数时会为实例增加一个指向最后原型的[[Prototype]]
指针,重写整个原型对象的话,会切断它们之间的分割(实例中的指针仅指向原型,不指向构造函数)。
function Student() {}var s1 = new Student();Student.prototype = { constructor: Student, name: "小刘", age: 36, sid: 2016, sayHi: function () { console.log("HI, My name is " + this.name); }};s1.sayHi(); // TypeError: s1.info is not a function
重写原型对象会切断现有原型与任何之前存在的对象实例之间的分割;它们援用的依然是最后的原型。
原生对象的原型
原生的援用类型都是采纳原型模式创立的。通过原生对象的原型,不仅能够获得所有默认办法的援用,而且还能够定义新办法。上面给String
类型增加startsWith()
办法。
String.prototype.startsWith = function (text) { return this.indexOf(text) == 0;};var msg = "Hello world!";console.log(msg.startsWith("Hello")); // trueconsole.log(msg.startsWith("world")); // false
但不举荐通过批改原生对象的原型来增加办法,这可能会导致命名抵触,而且会意外地重写原生办法。
原型对象的问题
原型对象的属性被实例共享,根本类型的值能够在实例上增加同名属性,暗藏原型中对应属性来解决,但对援用类型值,就会呈现问题。
function Student() {}Student.prototype = { constructor: Student, name: "小刘", age: 36, sid: 2016, friends: ["小燕", "小柒"], sayHi: function () { console.log("Hi, My name is " + this.name); }};var s1 = new Student();var s2 = new Student();s1.friends.push("小历");console.log(s1.friends); // [ '小燕', '小柒', '小历' ]console.log(s2.friends); // [ '小燕', '小柒', '小历' ]console.log(s1.friends == s2.friends); // true
s1
与s2
同时指向原型,在s1
中增加的元素也会反映到s2
中。
组合应用构造函数模式和原型模式
组合应用构造函数模式与原型模式是创立自定义类型最常见的形式。构造函数模式用于定义实例属性,原型模式定义办法和共享的属性。这种模式还反对构造函数的参数传递。
function Student(name, age, sid) { this.name = name; this.age = age; this.sid = sid; this.friends = ["小小", "小冷"];}Student.prototype = { constructor: Student, sayHi: function(){ console.log("Hi, My name is " + this.name); }}var s1 = new Student("小新", 29, 2020);var s2 = new Student("小霞", 19, 2012);s1.friends.push("小军");console.log(s1.friends); // ["小小", "小冷", "小军"]console.log(s2.friends); // ["小小", "小冷"]console.log(s1.friends === s2.friends); // falseconsole.log(s1.sayHi === s2.sayHi); // true
这种混合的模式是目前ES
中应用最宽泛、认同度最高的一种定义援用类型的模式。
动静原型模式
动静原型模式把所有信息都封装在构造函数中,在构造函数初始化时,通过查看某个应该存在的办法是否无效,来决定是否须要初始化原型。
function Student(name, age, sid) { // 属性 this.name = name; this.age =age; this.sid = sid; // 办法 if (typeof this.sayHi != "function") { Student.prototype.sayHi = function() { console.log("Hi" + this.name); } }}
这种形式只有在sayHi
办法不存在的状况下,才会将它增加到原型中。只会在首次调用构造函数时才会执行。实现初始化后就不再批改。这里对原型做出的批改,会立刻在所有实例中反映;其次,if
语句查看的能够是初始化之后应该存在的任何属性或办法,不用挨个查看,只有查看其中一个即可。这种模式创立的对象能够应用instanceof
确定它的类型。
寄生构造函数模式
寄生(parasitic)构造函数模式的根本思维是创立一个函数,该函数仅仅用于封装创建对象的代码,而后返回新创建的对象。
function Student(name, age, sid) { var o = new Object(); o.name = name; o.age = age; o.sid = sid; o.sayHi = function() { console.log("Hi" + this.name); } return o;}var friend = new Student("小青", 22, 2018);friend.sayHi();
该模式与工厂模式简直一样,只是应用new
进行创立并将函数称为构造函数。构造函数不返回对象,默认也会返回一个新的对象,能够通过return
语句重写构造函数返回的值。
这种模式能够为不能间接批改的构造函数增加额定的属性和办法。
function SpecialArray() { // 创立数组 var values = new Array(); // 增加值 values.push.apply(values, arguments); // 增加办法 values.toPipedString = function() { return this.join("|"); } // 返回数组 return values;}var colors = new SpecialArray("red", "blue", "green");console.log(colors.toPipedString()); // red|blue|green
咱们为Array
数组的实例增加了toPipedString()
办法。
稳当构造函数模式
稳当对象(durable objects)指的是没有公共属性,而且其办法也不援用this
的对象。稳当对象适宜在一些平安的环境中(禁止应用this
和new
),或者在搁置数据被其它应用程序改变时应用。稳当构造函数与寄生构造函数相似,但有两点不同:一是新创建对象的实例办法不援用this
;而是不应用new
操作符调用构造函数。
function Student(name, age, sid) { // 创立要返回的对象 var o = new Object(); // 定义公有变量和函数 var name = name, age = age, sid = sid; // 增加办法 o.getName = function() { return name; }; return o;}var s1 = Student("小路", 52, 2017);console.log(s1.getName()); // 小路friends.name; // undefined
如下面的代码所示,想要获取对象的name
信息,只有调用getName
办法,没有别的形式拜访其数据成员。
与寄生构造函数模式相似,应用稳当构造函数模式创立的对象与构造函数之间也没有什么关系,因而instanceof
操作符对这种对象也没有意义。
类构造函数模式
ES6
引入了Class
的概念。通过class
关键字能够定义类。它能够看作一个语法糖,让对象原型的写法更加清晰、更靠近面向对象的语法。
class Student { constructor(name, age, sid) { this.name = name; this.age = age; this.sid = sid; this.friends = ["小蓝", "小白", "小黑"]; } sayHi() { console.log("Hi, My name is " + this.name); }}var s1 = new Student("小雷", 42, 2021);s1.friends.push("小绿");var s2 = new Student("小云", 28, 2022);console.log(s1.friends); // [ '小蓝', '小白', '小黑', '小绿' ]console.log(s2.friends); // [ '小蓝', '小白', '小黑' ]
class
中的constructor
对应ES5
中的构造函数;创立类的办法不须要应用function
关键字,而没有显示定义constructor
,默认会增加一个空的constructor
办法。
class Student {}// 等同class Student { constructor() {}}
ES6
的类能够看做是构造函数的另一种写法,类是function
类型,且类的prototype
对象的constructor
属性间接指向类自身。
typeof Student // functionStudent === Student.prototype.constructor // true
尽管类是函数,但和ES5
不同,不通过new
而间接调用类会导致类型谬误。
var s1 = Student("小冰", 22, 2022); // TypeError: Class constructor Student cannot be invoked without 'new'
另外,类外部所有定义的办法,都是不可枚举的。
继承
继承在OO语言中很常见,许多OO语言都反对接口继承和实现继承。ECMAScript函数没有签名,因而无奈实现接口继承,它只反对实现继承,但ECMAScript不通过class
继承,而是应用原型链来实现。
ES6
引入了class
语法,能够实现基于class
的继承。
原型链
原型链的根本思维是援用类型的所有属性和办法通过原型被另一个援用类型继承,这样层层递进,形成链条。
实现原型链的代码如下:
function SuperType() { this.property = true;}SuperType.prototype.getSuperValue = function() { return this.property;}function SubType() { this.subproperty = false;}// 将SuperType的实例赋值给SubType.prototypeSubType.prototype = new SuperType();SubType.prototype.getSubValue = function() { return this.subprototype;}var instance = new SubType();console.log(instance.getSuperValue()); // true
下面的代码次要是通过SuperType
的实例赋值给SubType.prototype
来实现继承。而所有的类型都是继承自Object
,而该继承也是通过原型链实现的。
咱们能够通过 instanceof
操作合乎isPrototypeOf()
办法来确定原型和实例之间的关系。
console.log(Object.prototype.isPrototypeOf(instance)); //trueconsole.log(SuperType.prototype.isPrototypeOf(instance)); //trueconsole.log(SubType.prototype.isPrototypeOf(instance)); //true
原型链还存在问题,例如援用类型的原型会被所有实例共享,而实例对援用类型中的属性的操作会反映到另一个实例上。
function SuperType(){ this.colors = ["red", "blue", "green"];}function SubType(){}SubType.prototype = new SuperType();var instance1 = new SubType();instance1.colors.push("black");console.log(instance1.colors); //"red,blue,green,black"var instance2 = new SubType(); console.log(instance2.colors); //"red,blue,green,black"
借用构造函数
借用构造函数(constructor stealing)是在子类型构造函数的外部调用超类型构造函数。
function SuperType() { this.colors = ["red", "blue", "green"];}function SubType() { // 继承了SuperType SuperType.call(this);}var instance1 = new SubType();instance1.colors.push("black");console.log(instance1.colors); // [ 'red', 'blue', 'green', 'black' ]var instance2 = new SubType();console.log(instance2.colors); // [ 'red', 'blue', 'green' ]
通过应用 call()
办法(或者apply()
)"借用"了超类型的构造函数。在创立新的SubType
实例环境下调用SuperType
的构造函数,因而,SubType
的每个实例都会具备SuperType
属性的正本。
但应用借用构造函数,会无奈实现函数复用;并且不能继承在超类型的原型中定义的属性和办法。
组合继承
组合继承(combination inheritance)是应用原型链实现对原型模式和办法的继承,通过借用构造函数来实现对实例属性的继承。通过在原型上定义方法实现函数复用,还能保障每个实例都有它本人的属性。
function SuperType(name) { this.name = name; this.colors = ["red", "blue", "green"];}SuperType.prototype.sayHi = function () { console.log("Hi, My name is " + this.name);};function SubType(name, age) { // 继承属性 SuperType.call(this, name); this.age = age;}// 继承办法SubType.prototype = new SuperType();// 重写SubType.prototype的constructor属性,指向本人的构造函数SubTypeSubType.prototype.constructor = SubType;SubType.prototype.sayAge = function(){ console.log("My age is " + this.age);};var instance1 = new SubType("小华", 29);instance1.colors.push("black");console.log(instance1.colors); // [ 'red', 'blue', 'green', 'black' ]instance1.sayHi(); // Hi, My name is 小华instance1.sayAge(); // My age is 29var instance2 = new SubType("小夏", 27);console.log(instance2.colors); // [ 'red', 'blue', 'green' ]instance2.sayHi(); // Hi, My name is 小夏instance2.sayAge(); // My age is 27
在这里,通过将SuperType
的实例赋值给SubType
的原型,让SubType
的实例别离有用各自的属性。
组合继承交融了原型链与借用构造函数的长处,防止了它们的毛病,是最罕用的继承模式。
原型式继承
原型式继承就是创立通过原型指向已有对象的新对象。
function object(o) { function F() {} F.prototype = o; return new F();}
实质上,object()
对传入其中的对象执行一次浅复制。
var student = { name: "小李", friends: ["小明", "小清", "小民"]};var anotherStudent = object(student);anotherStudent.name = "小汉";anotherStudent.friends.push("小唐");var yetAnotherStudent = object(student);yetAnotherStudent.name = "小晋";yetAnotherStudent.friends.push("小隋");console.log(student.friends); // [ '小明', '小清', '小民', '小唐', '小隋' ]
这种形式的继承会使以对象student
作为原型的原型链共享着援用类型值属性;咱们在其它的实例上批改了friends
数组的值,在原型上也会反映。
ES5
中新增Object.create()
办法标准了原型式继承。Object.create()
一共接管两个参数:一个用作新对象原型的对象;另一个为新对象定义额定属性的对象(可选)。
var anotherStudent = Object.create(student);anotherStudent.name = "小汉";anotherStudent.friends.push("小唐");var yetAnotherStudent = Object.create(student);yetAnotherStudent.name = "小晋";yetAnotherStudent.friends.push("小隋");console.log(student.friends); // [ '小明', '小清', '小民', '小唐', '小隋' ]
第二个参数的格局与Object.defineProperties()
办法的第二个参数格局雷同。
var anotherStudent = Object.create(student, { name: { value: "小宋" }});console.log(anotherStudent.name); // 小宋
寄生式继承
寄生式(parasitic)继承与原型式继承同一种思路,但能够在函数外部加强对象。
function createAnother(original) { var clone = object(original); // 通过调用函数创立一个新对象 clone.sayHi = function () { // 以某种形式来加强这个对象 console.log("Hi, My name is " + clone.name); } return clone; // 返回这个对象}
在下面的函数中咱们为对象新增了办法,来加强函数。
var student = { name: "小李", friends: ["小明", "小清", "小民"]};var anotherStudent = createAnother(student);anotherStudent.sayHi(); // Hi, My name is 小李
寄生式继承的形式并没有解决原型式继承的毛病,也不能做到函数复用,从而升高效率。
寄生组合式继承
寄生组合式继承,通过借用构造函数来继承属性,通过原型链的混成模式来继承办法。
// 该函数实现了寄生组合式继承的最简略模式。function inheritPrototype(subType, superType) { var prototype = object(superType.prototype); // 创建对象 prototype.constructor = subType; // 加强对象 subType.prototype = prototype; // 指定对象}// 父类初始化实例属性和原型属性function SuperType(name) { this.name = name; this.colors = ["red", "blue", "green"];}SuperType.prototype.sayHi = function () { console.log("Hi, My name is " + this.name);}// 借用构造函数传递增强子类实例的属性(反对传参和防止篡改)function SubType(name, age) { SuperType.call(this, name); this.age = age;}// 将父类原型指向子类inheritPrototype(SubType, SuperType);// 新增子类原型属性SubType.prototype.seyAge = function () { console.log("My age is " + this.age);}
这个例子的高效率体现在它只调用了一次SuperType
构造函数,并且因而防止了在SubType.prototype
下面创立不必要的、多余的属性。与此同时,原型链还能放弃不变;因而,还可能失常应用instanceof
和isPrototypeOf()
。
类继承
ES6
通过extends
关键字实现继承。子类必须在constructor
办法中调用super
办法,对父类的this
对象进行赋值。否则子类得不到this
对象,会报错。
class Person { constructor(name, age) { this.name = name; this.age = age; this.friends = ["小蓝", "小白", "小黑"]; } sayHi() { console.log("Hi, My name is " + this.name); }}class Student extends Person{ constructor(name, age, sid) { super(name, age); this.sid = sid; }}
下面代码中,constructor
办法呈现了super
关键字,它在这里示意父类的构造函数,用来新建父类的this
对象。
总结
ECMAScript反对面向对象,但不应用类或者接口。对象在代码执行过程中创立和加强。在没有类的状况下,采纳的是工厂模式、构造函数模式、原型模式等创建对象。而从ES6
开始能够应用class
创建对象。
JavaScript次要通过原型链实现继承。而原型链的构建是通过将一个类型的实例赋值给另一个构造函数的原型来实现。提供的是原型式继承、寄生式继承和两者组合继承。而从ES6
开始应用class
与extends
关键字来实现类的继承形式。
更多内容请关注公众号「海人的博客」,回复「资源」即可取得收费学习资源!