对象和函数的原型
认识对象的原型
JavaScript当中每个对象都有一个特殊的内置属性 [[prototype]],这个特殊的对象可以指向另外一个对象。
那么这个对象有什么用呢?
- 当我们通过引用对象的属性key来获取一个value时,它会触发 [[Get]]的操作;
- 这个操作会首先检查该对象是否有对应的属性,如果有的话就使用它;
- 如果对象中没有改属性,那么会访问对象[[prototype]]内置属性指向的对象上的属性;
那么如果通过字面量直接创建一个对象,这个对象也会有这样的属性吗?如果有,应该如何获取这个属性呢?
- 答案是有的,只要是对象都会有这样的一个内置属性;
获取的方式有两种:
- 方式一:通过对象的 __proto__
属性可以获取到(但是这个是早期浏览器自己添加的,存在一定的兼容性问题);
- 方式二:通过 Object.getPrototypeOf 方法可以获取到;
var obj = {
name: "what",
age: 15,
};
console.log(obj);
var info = {};
// 获取对象的原型
console.log(obj.__proto__);
console.log(Object.getPrototypeOf(obj));
console.log(obj.__proto__ === Object.getPrototypeOf(obj)); // true
// 疑问: 这个原型有什么用?
/*
当我们通过 [[get]] 方式来获取一个属性对应的value时
1.它会优先在自己的对象中查找,如果找到直接返回
2.如果没有找到,会在原型对象中查找
*/
console.log(obj.name);
obj.__proto__.message = "hello world"
console.log(obj.message);
函数的原型 prototype
那么我们知道上面的东西对于我们的构造函数创建对象来说有什么用呢?
- 它的意义是非常重大的,接下来我们继续来探讨;
这里我们又要引入一个新的概念:所有的函数都有一个prototype的属性(注意:不是__proto__
)
你可能会问题,是不是因为函数是一个对象,所以它有prototype的属性呢?
- 不是的,因为它是一个函数,才有了这个特殊的属性;
- 而不是它是一个对象,所以有这个特殊的属性;
var obj = {};
function foo() {}
// 1.将函数当成一个一个普通的对象时,它是具备 __proto__ (隐式原型)
// 作用: 查找key对应的value时,会找到原型身上
// console.log(obj.__proto__);
// console.log(foo.__proto__);
// 2.将函数当成一个函数时,它是具备 prototype 的
console.log(foo.prototype);
new、constructor
再看new操作符
new关键字的步骤如下:
- 在内存中创建一个新的对象(空对象);
- 这个对象内部的[[prototype]]属性会被赋值为该构造函数的prototype属性;
那么也就意味着我们通过Person构造函数创建出来的所有对象的[[prototype]]属性都指向Person.prototype:
/*
1.什么是函数的显式原型
用来区分和对象原型的区别
2.函数的原型的作用
再通过 new 操作符创建对象时,将这个显式原型赋值给创建出来的对象的隐式原型
3.案例Person,将所有的函数定义放到了显式原型上
*/
function Student(name, age, sno) {
this.name = name;
this.age = age;
this.sno = sno;
// 1.方式一:编写函数,会创建很多歌函数对象
// this.running = function () {
// console.log(this.name + " running");
// };
// this.eating = function () {
// console.log(this.name + " eating");
// };
// this.studying = function () {
// console.log(this.name + " studying");
// };
}
// 当我们多个对象拥有共同的值时,我们可以将它放在构造函数对象的显式原型上
// 由构造函数创建出来的所有对象,都会共享这些属性
Student.prototype.running = function () {
console.log(this.name + " running");
};
Student.prototype.eating = function () {
console.log(this.name + " eating");
};
// 1.创建三个学生
var stu1 = new Student("why", 18, 111);
var stu2 = new Student("whose", 16, 222);
var stu3 = new Student("what", 20, 333);
/* 隐式原型的作用
1. stu1的隐式原型是? Student.prototype 对象
2. stu1.running 查找:
先在自己身上查找,没有找到
去原型上查找
*/
stu1.running();
stu2.eating();
创建对象的内存表现
prototype添加属性
新增属性
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.running = function () {
console.log("running~");
};
var p1 = new Person("why", 18);
var p2 = new Person("what", 30);
// 进行操作
console.log(p1.name);
console.log(p2.name);
p1.running();
p2.running();
// 新增属性
Person.prototype.address = "日本";
p1.__proto__.info = "东京帅哥";
p1.height = 1.88;
p2.isAdmin = true;
console.log(p1.address);
console.log(p2.isAdmin);
console.log(p1.isAdmin);
console.log(p2.info);
// 修改 address
p1.address = "东京";
console.log(p2.address);
constructor属性
事实上原型对象上面是有一个属性的:constructor
- 默认情况下原型上都会添加一个属性叫做constructor,这个constructor指向当前的函数对象;
重写原型对象
如果我们需要在原型上添加过多的属性,通常我们会重写整个原型对象
前面我们说过, 每创建一个函数, 就会同时创建它的prototype对象, 这个对象也会自动获取constructor属性;
- 而我们这里相当于给prototype重新赋值了一个对象, 那么这个新对象的constructor属性, 会指向Object构造函数, 而不是Person构造函数了
原型对象的constructor
如果希望constructor指向Person,那么可以手动添加:
上面的方式虽然可以, 但是也会造成constructor的[[Enumerable]]特性被设置了true.
- 默认情况下, 原生的constructor属性是不可枚举的.
- 如果希望解决这个问题, 就可以使用我们前面介绍的Object.defineProperty()函数了.
创建对象 – 构造函数和原型组合
我们在上一个构造函数的方式创建对象时,有一个弊端:会创建出重复的函数,比如running、eating这些函数
- 那么有没有办法让所有的对象去共享这些函数呢?
- 可以,将这些函数放到Person.prototype的对象上即可
function Person() {}
console.log(Person.prototype);
// 在原有的原型对象上添加新的属性
// Person.prototype.message = "Hello Person";
// Person.prototype.info = { name: "hhhh", age: 23 };
// Person.prototype.running = function () {};
// Person.prototype.eating = function () {};
// console.log(Person.prototype);
// console.log(Object.keys(Person.prototype));
console.log(
Object.getOwnPropertyDescriptor(Person.prototype, "constructor")
);
// 直接赋值一个新的原型对象
Person.prototype = {
message: "Hello Person",
info: { name: "hhhh", age: 23 },
running: function () {},
eating: function () {},
// constructor: Person,
};
Object.defineProperty(Person, "constructor", {
writable: true,
enumerable: false,
configurable: true,
value: Person,
});
console.log(Object.keys(Person.prototype));
// 新建实例对象
var p1 = new Person();
console.log(p1.message);
面向对象的特性 – 继承
面向对象有三大特性:封装、继承、多态
- 封装:我们前面将属性和方法封装到一个类中,可以称之为封装的过程;
- 继承:继承是面向对象中非常重要的,不仅仅可以减少重复代码的数量,也是多态前提(纯面向对象中);
- 多态:不同的对象在执行时表现出不同的形态;
这里我们核心讲继承。
那么继承是做什么呢?
- 继承可以帮助我们将重复的代码和逻辑抽取到父类中,子类只需要直接继承过来使用即可;
- 在很多编程语言中,继承也是多态的前提;
JavaScript当中如何实现继承呢?
- 不着急,我们先来看一下JavaScript原型链的机制;
- 再利用原型链的机制实现一下继承;
JavaScript原型链
在真正实现继承之前,我们先来理解一个非常重要的概念:原型链。
- 我们知道,从一个对象上获取属性,如果在当前对象中没有获取到就会去它的原型上面获取
Object的原型
那么什么地方是原型链的尽头呢?比如第三个对象是否也是有原型__proto__
属性呢?
我们会发现它打印的是 [Object: null prototype] {}
- 事实上这个原型就是我们最顶层的原型了
- 从Object直接创建出来的对象的原型都是 [Object: null prototype] {}。
那么我们可能会问题: [Object: null prototype] {} 原型有什么特殊吗?
特殊一:该对象有原型属性,但是它的原型属性已经指向的是null,也就是已经是顶层原型了;
特殊二:该对象上有很多默认的属性和方法;
创建Object对象的内存图
原型链关系的内存图
Object是所有类的父类
从我们上面的Object原型我们可以得出一个结论:原型链最顶层的原型对象就是Object的原型对象
function Person() {}
function Student() {}
function Teacher() {}
inherit(Student, Person);
console.log(Person.prototype.__proto__ === Object.prototype);
// 在 Object的原型上添加属性
Object.prototype.message = "what";
var stu = new Student();
console.log(stu.message);
// Object原型上本来就已经存在一些方法
console.log(Object.prototype)
console.log(stu.toString())
// 函数对象也是最终继承自Object
通过原型链实现继承
如果我们现在需要实现继承,那么就可以利用原型链来实现了:
- 目前stu的原型是p对象,而p对象的原型是Person默认的原型,里面包含running等函数;
- 注意:步骤4和步骤5不可以调整顺序,否则会有问题
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.running = function () {
console.log("running~");
};
Person.prototype.eating = function () {
console.log("eating~");
};
// 定义学生类
function Student(name, age, sno, score) {
this.sno = sno;
this.score = score;
}
// 方式一:父类原型直接赋值给子类的原型
// 缺点:父类和子类共享一个原型对象,修改了任何一个,另一个也会被修改
// Student.prototype = Person.prototype;
// 方式二: 创建一个父类的实例对象(new Person()),用这个实例对象去作为子类的原型对象
var p = new Person("why", 18);
Student.prototype = p;
Student.prototype.studying = function () {
console.log("studying~");
};
// 创建学生
var stu1 = new Student("why", 19, 136, 123);
stu1.running();
stu1.studying();
console.log(stu1.name, stu1.age);
继承创建对象的内存图
原型链继承的弊端
但是目前有一个很大的弊端:某些属性其实是保存在p对象上的;
- 第一: 我们通过直接打印对象是看不到这个属性的;
- 第二: 这个属性会被多个对象共享,如果这个对象是一个引用类型,那么就会造成问题;
- 第三: 不能给Person传递参数(让每个stu有自己的属性),因为这个对象是一次性创建的(没办法定制化);
借用构造函数继承
为了解决原型链继承中存在的问题,开发人员提供了一种新的技术: constructor stealing(有很多名称: 借用构造函数或者称之为经典继承或者称之为伪造对象):
- steal是偷窃、剽窃的意思,但是这里可以翻译成借用;
借用继承的做法非常简单:在子类型构造函数的内部调用父类型构造函数.
因为函数可以在任意的时刻被调用;
因此通过apply()和call()方法也可以在新创建的对象上执行构造函数;
组合借用继承的问题
组合继承是JavaScript最常用的继承模式之一:
- 如果你理解到这里, 点到为止, 那么组合来实现继承只能说问题不大;
- 但是它依然不是很完美,但是基本已经没有问题了;
组合继承存在什么问题呢?
- 组合继承最大的问题就是无论在什么情况下,都会调用两次父类构造函数。
- 一次在创建子类原型的时候;
- 另一次在子类构造函数内部(也就是每次创建子类实例的时候);
- 另外,如果你仔细按照我的流程走了上面的每一个步骤,你会发现:所有的子类实例事实上会拥有两份父类的属性
- 一份在当前的实例自己里面(也就是person本身的),另一份在子类对应的原型对象中(也就是
person.__proto__
里面); - 当然,这两份属性我们无需担心访问出现问题,因为默认一定是访问实例本身这一部分的;
- 一份在当前的实例自己里面(也就是person本身的),另一份在子类对应的原型对象中(也就是
function Person(name, age, height, address) {
this.name = name;
this.age = age;
this.height = height;
this.address = address;
}
Person.prototype.running = function () {
console.log("running~");
};
Person.prototype.eating = function () {
console.log("eating~");
};
// 定义学生类
function Student(name, age, height, address, sno, score) {
// 重点: 借用构造函数
Person.call(this, name, age, height, address);
this.sno = sno;
this.score = score;
}
// 方式一:父类原型直接赋值给子类的原型
// 缺点:父类和子类共享一个原型对象,修改了任何一个,另一个也会被修改
// Student.prototype = Person.prototype;
// 方式二: 创建一个父类的实例对象(new Person()),用这个实例对象去作为子类的原型对象
var p = new Person("why", 18);
Student.prototype = p;
Student.prototype.studying = function () {
console.log("studying~");
};
// 创建学生
var stu1 = new Student("why", 19, 1.88, "东京", 136, 123);
var stu2 = new Student("what", 29, 1.88, "东京", 136, 100);
stu1.running();
stu1.studying();
console.log(stu1, stu2);
console.log(stu1.name, stu1.age);
console.log(stu2.name, stu2.age);
原型式继承函数
原型式继承的渊源
- 这种模式要从道格拉斯·克罗克福德(Douglas Crockford,著名的前端大师,JSON的创立者)在2006年写的一篇文章说起:Prototypal Inheritance in JavaScript(在JavaScript中使用原型式继承)
- 在这篇文章中,它介绍了一种继承方法,而且这种继承方法不是通过构造函数来实现的.
- 为了理解这种方式,我们先再次回顾一下JavaScript想实现继承的目的:重复利用另外一个对象的属性和方法.
最终的目的:student对象的原型指向了person对象;
寄生式继承函数
寄生式(Parasitic)继承
- 寄生式(Parasitic)继承是与原型式继承紧密相关的一种思想, 并且同样由道格拉斯·克罗克福德(Douglas Crockford)提出和推广的;
- 寄生式继承的思路是结合原型类继承和工厂模式的一种方式;
- 即创建一个封装继承过程的函数, 该函数在内部以某种方式来增强对象,最后再将这个对象返回;
寄生组合式继承
现在我们来回顾一下之前提出的比较理想的组合继承
- 组合继承是比较理想的继承方式, 但是存在两个问题:
- 问题一: 构造函数会被调用两次: 一次在创建子类型原型对象的时候, 一次在创建子类型实例的时候.
- 问题二: 父类型中的属性会有两份: 一份在原型对象中, 一份在子类型实例中.
事实上, 我们现在可以利用寄生式继承将这两个问题给解决掉.
- 你需要先明确一点: 当我们在子类型的构造函数中调用父类型.call(this, 参数)这个函数的时候, 就会将父类型中的属性和方法复制一份到了子类型中. 所以父类型本身里面的内容, 我们不再需要.
- 这个时候, 我们还需要获取到一份父类型的原型对象中的属性和方法.
- 能不能直接让子类型的原型对象 = 父类型的原型对象呢?
- 不要这么做, 因为这么做意味着以后修改了子类型原型对象的某个引用类型的时候, 父类型原生对象的引用类型也会被修改.
- 我们使用前面的寄生式思想就可以了
/*
满足什么条件:
1.必须创建出来一个对象
2.这个对象的隐式原型必须指向父类的显式原型
3.将这个对象赋值给子类的显示原型
*/
// 封装工具函数
// 创建对象的过程
function createObject(o) {
function F() {}
F.prototype = o;
return new F();
}
// 将Subtype和Supertype联系在一起
function inherit(Subtype, Supertype) {
Subtype.prototype = createObject(Supertype.prototype);
Object.defineProperty(Subtype.prototype, "constructor", {
enumerable: false,
configurable: true,
writable: true,
value: Subtype,
});
}
function Person(name, age, height) {}
function Student() {}
// 1.之前的做法:但是不够好,会调用两次构造函数
/* var p = new Person()
Student.prototype = p */
// 方案一:
var obj = {};
// obj.__proto__ = Person.prototype;
Object.setPrototypeOf(obj, Person.prototype);
Student.prototype = obj;
// 方案二:
function F() {}
F.prototype = Person.prototype;
Student.prototype = new F();
// 方案三
var obj = Object.create(Person.prototype);
console.log(obj.__proto__ === Person.prototype);
Student.prototype = obj;
// 方案四
inherit(Student, Person);
寄生组合继承的代码
inherit_utils.js
function createObject(o) {
function F() {}
F.prototype = o;
return new F();
}
// 将Subtype和Supertype联系在一起
function inherit(Subtype, Supertype) {
Subtype.prototype = createObject(Supertype.prototype);
Object.defineProperty(Subtype.prototype, "constructor", {
enumerable: false,
configurable: true,
writable: true,
value: Subtype,
});
}
最终继承方案的写法
<script src="./js/inherit_utils.js"></script>
<script>
/*
寄生组合式继承
原型链/借用/原型式(对象之间)/寄生式函数
*/
function Person(name, age, height) {
this.name = name;
this.age = age;
this.height = height;
}
Person.prototype.running = function () {
console.log("running~");
};
Person.prototype.eating = function () {
console.log("eating~");
};
function Student(name, age, height, sno, score) {
Person.call(this, name, age, height);
this.sno = sno;
this.score = score;
}
inherit(Student, Person);
Student.prototype.studying = function () {
console.log("studying");
};
// 创建实例对象
var stu1 = new Student("what", 16, 1.55, 111, 100);
var stu2 = new Student("whose", 17, 1.75, 111, 96);
console.log(stu1, stu2);
</script>
对象的方法补充
hasOwnProperty
- 对象是否有某一个属于自己的属性(不是在原型上的属性)
in/for in 操作符
- 判断某个属性是否在某个对象或者对象的原型上
instanceof
- 用于检测构造函数(Person、Student类)的pototype,是否出现在某个实例对象的原型链上
isPrototypeOf
- 用于检测某个对象,是否出现在某个实例对象的原型链上
var obj = {
name: "why",
age: 18,
};
var info = createObject(obj);
info.address = "中国";
info.intro = "大好河山";
console.log(info.name, info.address);
console.log(info);
// 1.hasOwnProperty
console.log(info.hasOwnProperty("name")); // false
console.log(info.hasOwnProperty("address")); // true
// 2.in操作符
console.log("name" in info);
console.log("address" in info);
// 注意: for in 方法不止遍历的自己的对象的内容,也包括原型上面的内容
for (var key in info) {
console.log(key);
}
// 3.instanceof
// instanceof 用于判断对象和类之间的关系
function Person() {}
function Student() {}
inherit(Student, Person);
// stu实例(instance)对象
var stu = new Student();
console.log(stu instanceof Student);
console.log(stu instanceof Person);
console.log(stu instanceof Object);
console.log(stu instanceof Array);
// isPrototypeOf
console.log(Student.prototype.isPrototypeOf(stu))
// 可以用来判断对象之间的继承
console.log(obj.isPrototypeOf(info))
原型继承关系
- p1 是 Person的实例对象
- obj 是 Object 的实例对象
- Function/Object/Foo 都是Function的实例对象
- 原型对象默认创建时,隐式原型都是指向Object的显示原型的(Object指向null)
- 推导另一个结论: Object 是 Person/Function的父类, Function是Object的构造函数
var obj = {}; // new Object()
obj.__proto__; // Object.prototype
function foo() {} // new Function()
console.log(foo.length, foo.name);
console.log(foo.__proto__); // Function.prototype
// Person.__proto__ === Function.prototype
function Person() {}
console.log(foo.__proto__ === Function.prototype);
console.log(Person.__proto__ === Function.prototype);
console.log(foo.__proto__ === Person.__proto__);
console.log(Object.__proto__ === Function.prototype);
console.log(Function.__proto__ === Function.prototype);
var p1 = new Person();
var p2 = new Person();
console.log(Object.prototype);
类方法和示例方法
function Person(name, age) {
this.name = name;
this.age = age;
}
// 添加到 Person 原型上的方法也称为 实例方法
Person.prototype.running = function () {
console.log(this.name + "running~");
};
Person.prototype.eating = function () {
console.log("eating~");
};
Person.totalCounter = "70亿";
// 添加到 Person对象本省的方法也称为 类方法
var names = ["abc", "cba", "mba", "nba"];
Person.randomPerson = function () {
var randomName = names[Math.floor(Math.random() * names.length)];
return new Person(randomName, Math.floor(Math.random() * 100));
};
// 实例对象
var p1 = new Person("why", 16);
var p2 = new Person("what", 19);
p1.running();
// 没有实例对象的情况下,不可以调用
var p = Person.randomPerson();
console.log(p);
认识class定义类
我们会发现,按照前面的构造函数形式创建 类,不仅仅和编写普通的函数过于相似,而且代码并不容易理解。
- 在ES6(ECMAScript2015)新的标准中使用了class关键字来直接定义类;
- 但是类本质上依然是前面所讲的构造函数、原型链的语法糖而已;
- 所以学好了前面的构造函数、原型链更有利于我们理解类的概念和继承关系;
那么,如何使用class来定义一个类呢?
- 可以使用两种方式来声明类:类声明和类表达式
class Person {
// 1.类中的构造函数
// 当我们通过new 关键字调用一个Person类是,默认调用class中的constructor函数
constructor(name, age) {
this.name = name;
this.age = age;
}
// 2.实例方法, 本质上还是放在 prototype 上
running() {
console.log(this.name + "running~");
}
eating() {
console.log(this.name + "eating~");
}
}
// 创建实例对象
var p1 = new Person("what", 17);
// 使用实例对象中属性和方法
console.log(p1.name, p1.age);
p1.running()
p1.eating()
// 研究
console.log(Person.prototype === p1.__proto__);
// console.log(Person.running()) 错误
类和构造函数的异同
我们来研究一下类的一些特性:
- 你会发现它和我们的构造函数的特性其实是一致的;
类的构造函数
如果我们希望在创建对象的时候给类传递一些参数,这个时候应该如何做呢?
- 每个类都可以有一个自己的构造函数(方法),这个方法的名称是固定的constructor;
- 当我们通过new操作符,操作一个类的时候会调用这个类的构造函数constructor;
- 每个类只能有一个构造函数,如果包含多个构造函数,那么会抛出异常;
当我们通过new关键字操作类的时候,会调用这个constructor函数,并且执行如下操作:
- 在内存中创建一个新的对象(空对象);
- 这个对象内部的[[prototype]]属性会被赋值为该类的prototype属性;
- 构造函数内部的this,会指向创建出来的新对象;
- 执行构造函数的内部代码(函数体代码);
- 如果构造函数没有返回非空对象,则返回创建出来的新对象;
类的实例方法
在上面我们定义的属性都是直接放到了this上,也就意味着它是放到了创建出来的新对象中:
- 在前面我们说过对于实例的方法,我们是希望放到原型上的,这样可以被多个实例来共享;
- 这个时候我们可以直接在类中定义;
// function定义类
function Person1(name, age) {
this.name = name;
this.age = age;
}
Person1.prototype.running = function () {};
Person1.prototype.eating = function () {};
var p1 = new Person1();
console.log(p1.__proto__ === Person1.prototype);
console.log(Person1.__proto__ === Function.prototype);
console.log(Person1.prototype.constructor);
console.log(typeof Person1); // function
// 不同点: 作为普通函数去调用
Person1("abc", 199);
// class 定义类
class Person2 {
constructor(name, age) {
this.name = name;
this.age = age;
}
running() {}
eating() {}
}
var p2 = new Person2("whose", 16);
console.log(p2.__proto__ === Person2.prototype);
console.log(Person2.prototype.constructor);
console.log(typeof Person2); // function
// 不通电:class定义的类,不能作为一个普通的函数进行调用
Person2("cba", 45);
类的访问器方法
我们之前讲对象的属性描述符时有讲过对象可以添加setter和getter函数的,那么类也是可以的:
class Person {
constructor(name, age) {
// 约定以_开头的属性和方法,是不在外界访问的
this._name = name;
}
set name(value) {
console.log("设置name");
this._name = value;
}
get name() {
console.log("获取name");
return this._name;
}
}
var p1 = new Person("why", 18);
p1.name = "what";
console.log(p1.name);
// console.log(p1._name)
var p2 = new Person("what", 128);
console.log(p2.name);
// 2.访问器的应用场景
class Rectangle {
constructor(x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
get position() {
return { x: this.x, y: this.y };
}
get size() {
return { width: this.width, height: this.height };
}
}
var rect1 = new Rectangle(10, 20, 100, 200);
console.log(rect1.position);
console.log(rect1.size);
类的静态方法
静态方法通常用于定义直接使用类来执行的方法,不需要有类的实例,使用static关键字来定义:
function Person1() {}
// 实例方法
Person1.prototype.running = function () {};
// 类方法
var names = ["abc", "cba", "mba", "nba"];
Person1.randomPerson = function () {
var randomName = names[Math.floor(Math.random() * names.length)];
return new Person1(randomName, Math.floor(Math.random() * 100));
};
var p1 = new Person1();
p1.running();
Person1.randomPerson();
// class定义的类
class Person2 {
constructor(name, age) {
this.name = name;
this.age = age;
}
running() {
console.log(this.name + " running");
}
eating() {}
// 类方法(静态方法)
static randomPerson() {
console.log(this);
var randomName = names[Math.floor(Math.random() * names.length)];
return new this(randomName, Math.floor(Math.random() * 100));
}
}
var p2 = new Person2();
p2.running();
p2.eating();
var randomPerson = Person2.randomPerson();
console.log(randomPerson);
ES6类的继承 - extends
前面我们花了很大的篇幅讨论了在ES5中实现继承的方案,虽然最终实现了相对满意的继承机制,但是过程却依然是非常繁琐的。
- 在ES6中新增了使用extends关键字,可以方便的帮助我们实现继承:
super关键字
我们会发现在上面的代码中我使用了一个super关键字,这个super关键字有不同的使用方式:
- 注意:在子(派生)类的构造函数中使用this或者返回默认对象之前,必须先通过super调用父类的构造函数!
- super的使用位置有三个:子类的构造函数、实例方法、静态方法;
// 定义父类
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
running() {
console.log("running~");
}
eating() {
console.log("eating~");
}
}
class Student extends Person {
constructor(name, age, sno, score) {
super(name,age)
// this.name = name;
// this.age = age;
this.sno = sno;
this.score = score;
}
/* running() {
console.log("running~");
}
eating() {
console.log("eating~");
} */
studying() {
console.log("studying~");
}
}
var stu1 = new Student('why',11,100,120)
stu1.running()
stu1.eating()
stu1.studying()
class Teacher extends Person {
constructor(name, age, title) {
super(name,age)
// this.name = name;
// this.age = age;
this.title = title;
}
/* running() {
console.log("running~");
}
eating() {
console.log("eating~");
} */
teaching() {
console.log("teaching~");
}
}
class Animal {
constructor() {}
running() {
console.log("running");
}
eating() {
console.log("eating");
}
static sleep(){
console.log('static Animal sleep')
}
}
class Dog extends Animal {
// 子类重写父类方法
running() {
// 调用父类方法
super.eating();
console.log("dog四条腿running");
}
static sleep(){
console.log('趴着')
super.sleep()
}
}
var dog = new Dog();
dog.running();
dog.eating();
Dog.sleep()
继承内置类
我们也可以让我们的类继承自内置类,比如Array:
// 1.创建新的类,继承自Array进行扩展
class RinArray extends Array {
get lastItem() {
return this[this.length - 1];
}
get firstItem() {
return this[0];
}
}
var arr = new RinArray(10, 20, 30);
console.log(arr);
console.log(arr.length);
console.log(arr[0]);
console.log(arr.lastItem);
console.log(arr.firstItem);
// 2.直接对Array进行扩展
Array.prototype.lastItem = function () {
return this[this.length - 1];
};
var arr = new Array(12, 22, 32);
console.log(arr.__proto__ === Array.prototype);
console.log(arr.lastItem());
类的混入mixin
JavaScript的类只支持单继承:也就是只能有一个父类
- 那么在开发中我们我们需要在一个类中添加更多相似的功能时,应该如何来做呢?
- 这个时候我们可以使用混入(mixin);
// JavaScript 只支持单继承
function mixinAnimal(BaseClass) {
return class extends BaseClass {
running() {
console.log("running~");
}
};
}
function mixinRunner(BaseClass) {
return class extends BaseClass {
flying() {
console.log("flying~");
}
};
}
class Bird {
eating() {
console.log("eating~");
}
}
// var NewBird = mixinRunner(mixinAnimal(Bird));
class NewBird extends mixinRunner(mixinAnimal(Bird)) {}
var bird = new NewBird();
bird.flying();
bird.running();
bird.eating();
Object.assign(Bird.prototype, {});
babel 可以将ES6转成ES5代码
JavaScript中的多态
面向对象的三大特性:封装、继承、多态。
- 前面两个我们都已经详细解析过了,接下来我们讨论一下JavaScript的多态。
JavaScript有多态吗?
- 维基百科对多态的定义:多态(英语:polymorphism)指为不同数据类型的实体提供统一的接口,或使用一个单一的符号来表示多个不同的类型。
- 非常的抽象,个人的总结:不同的数据类型进行同一个操作,表现出不同的行为,就是多态的体现。
那么从上面的定义来看,JavaScript是一定存在多态的。
严格意义上的多态
// 继承是多态的前提
// shape 形状
class Shape {
getArea() {}
}
class Rectangle extends Shape {
constructor(width, height) {
super();
this.width = width;
this.height = height;
}
getArea() {
return this.width * this.height;
}
}
class Circle extends Shape {
constructor(radius) {
super();
this.radius = radius;
}
getArea() {
return this.radius * this.radius * 3.14;
}
}
var rect1 = new Rectangle(100, 200);
var rect2 = new Rectangle(20, 30);
var c1 = new Circle(10);
var c2 = new Circle(15);
/*
在严格意义的面向对象语言中,多态的是存在如下条件的
1.必须有继承(实现接口)
2.必须有父类引用指向子类对象
*/
function getShapeArea(shape) {
console.log(shape.getArea());
}
getShapeArea(rect1);
getShapeArea(c1);
JavaScript 中的多态
function sum(a1, a2) {
return a1 + a2;
}
sum(20, 30);
sum("abc", "cba");
// 多态的表现
var foo = 123;
foo = "hello world";
console.log(foo.split());
foo = {
running: function () {},
};
foo.running();
foo = [];
console.log(foo.length);
对象字面量的增强
ES6中对 [[对象字面量]] 进行了增强, 称之为 Enhanced object literals (增强对象字面量)
字面量的增强主要包括下面几个部分:
- 属性的简写: Property Shorthand
- 方法的简写: Method Shorthand
- 计算属性名: Computed Property Names
// 1.属性的增强
// 2.方法的增强
// 3.计算属性的写法
var name = "what";
var age = 12;
var key = "address" + " city";
var obj = {
// 属性增强
name,
age,
running: function () {
console.log(this);
},
// 方法增强
swimming() {
console.log(this);
},
eating: () => {
console.log(this);
},
// 计算属性名
[key]: "广州",
};
obj.running();
obj.swimming();
obj.eating();
function foo() {
var message = "hello world";
var info = "my name is what";
return { message, info };
}
var result = foo();
console.log(result.message, result.info);
解构 Destructuring
ES6中新增了一个从数组或者对象中方便获取数据的方法, 称之为[解构]
- 解构赋值 是一种特殊的语法, 它使我们可以将数组或者对象 “拆包” 至一系列变量中
我们可以划分为: 数组的结构和对象的结构
解构的应用场景
解构目前在开发中使用是非常多的
- 比如在开发中拿到一个变量时,自动对其进行解构使用
- 比如对函数的参数进行解构
var names = ["abc", "cba", undefined, "mba", "nba"];
var obj = { name: "what", age: 18, height: 1.82 };
// 1.数组的解构
var name1 = names[0];
var name2 = names[1];
var name3 = names[2];
// 1.1 基本使用
var [name1, name2, name3] = names;
console.log(name1, name2, name3);
// 1.2 顺序问题: 数组有严格的顺序
var [name1, , name3] = names;
console.log(name1, name3);
// 1.3 解构出数组
var [name1, name2, ...newNames] = names;
console.log(name1, name2, ...newNames);
// 1.4 解构的默认值
var [name1, name2, name3 = "default"] = names;
console.log(name1, name2, name3);
// 2.对象的解构
var name = obj.name;
var age = obj.age;
var height = obj.height;
// 2.1 基本使用
var { name, age, height } = obj;
console.log(name, age, height);
// 2.2 顺序问题:对象的解构是没有顺序的, 根据 key 解构
var { height, name, age } = obj;
console.log(name, age, height);
// 2.3 对变量重命名
var { height: wHeight, name: wName, age: wAge } = obj;
console.log(wHeight, wName, wAge);
// 2.4 默认值
var {
height: wHeight,
name: wName,
age: wAge,
address: wAddress = "广州",
} = obj;
console.log(wHeight, wName, wAge, wAddress);
// 2.5 对象的剩余内容
var { height: wHeight, name: wName, ...newObj } = obj;
console.log(newObj);
// 应用: 在函数中(其他类似的地方)
function getPosition({ x, y }) {
console.log(x, y);
}
getPosition({ x: 10, y: 20 });
getPosition({ x: 25, y: 35 });
手写call/apply
function foo(name, age) {
console.log(this, name, age);
}
// foo.apply("aaa", ["what", 12]);
// foo.call("bbb", "what", 12);
// 1.给函数对象添加方法
Function.prototype.rapply = function (thisArg, otherArg) {
// this -> 调用的函数对象
// thisArg -> 传入的第一个参数,要绑定的this
// console.log(this); // -> 当前调用的函数对象
// this.apply(thisArg);
// 1.获取 thisArg, 并且确保是一个对象类型
thisArg =
thisArg === null || thisArg === undefined ? window : Object(thisArg);
// thisArg.fn = this;
Object.defineProperty(thisArg, "fn", {
enumerable: false,
configurable: true,
value: this,
});
thisArg.fn(...otherArg);
delete thisArg.fn;
};
foo.rapply({ name: "what" }, ["kin", 18]);
foo.rapply("abc", ["kin", 18]);
foo.rapply(null, ["rin", 11]);
// 2.给函数对象添加方法: rcall
Function.prototype.rcall = function (thisArg, ...otherArg) {
// 1.获取 thisArg, 并且确保是一个对象类型
thisArg =
thisArg === null || thisArg === undefined ? window : Object(thisArg);
// thisArg.fn = this;
Object.defineProperty(thisArg, "fn", {
enumerable: false,
configurable: true,
value: this,
});
thisArg.fn(...otherArg);
delete thisArg.fn;
};
foo.rcall({ name: "what" }, "kin", 18);
foo.rcall("abc", "kin", 18);
foo.rcall(null, "rin", 11);
封装
function foo(name, age) {
console.log(this, name, age);
}
function execFn(thisArg, otherArg, fn) {
// 1.获取 thisArg, 并且确保是一个对象类型
thisArg =
thisArg === null || thisArg === undefined ? window : Object(thisArg);
// thisArg.fn = this;
Object.defineProperty(thisArg, "fn", {
enumerable: false,
configurable: true,
value: this,
});
thisArg.fn(...otherArg);
delete thisArg.fn;
}
// 1.给函数对象添加方法
Function.prototype.rapply = function (thisArg, otherArg) {
execFn(thisArg, otherArg, this);
};
foo.rapply({ name: "what" }, ["kin", 18]);
foo.rapply("abc", ["kin", 18]);
foo.rapply(null, ["rin", 11]);
// 2.给函数对象添加方法: rcall
Function.prototype.rcall = function (thisArg, ...otherArg) {
execFn(thisArg, otherArg, this);
};
foo.rcall({ name: "what" }, "kin", 18);
foo.rcall("abc", "kin", 18);
foo.rcall(null, "rin", 11);
手写bind函数实现
function foo(name, age, height, address) {
console.log(this, name, age, height, address);
}
// Function.prototype
/* var newFoo = foo.bind({ name: "why" }, "why", 18);
newFoo(1.66); */
// 实现rbind函数
Function.prototype.rbind = function (thisArg, ...otherArgs) {
// console.log(this); // foo函数对象
thisArg =
thisArg === null || thisArg === undefined ? window : Object(thisArg);
Object.defineProperty(thisArg, "fn", {
enumerable: false,
configurable: true,
writable: false,
value: this,
});
return (...newArgs) => {
// var allArgs = otherArgs.concat(newArgs);
var allArgs = [...otherArgs, ...newArgs];
thisArg.fn(...allArgs);
// delete thisArg.fn; 不能删除,后面还会用到
};
};
var newFoo = foo.rbind('abc', "why", 21);
newFoo(1.88, "广州");
newFoo(1.68, "深圳");
Q.E.D.