Appearance
认识class定义类
我们会发现,按照前面的构造函数形式创建类,不仅仅和编写普通的函数过于相似,而且代码并不容易理解。
在ES6(ECMAScript2015)新的标准中使用了class关键字来直接定义类;
但是类本质上依然是前面所讲的构造函数、原型链的语法糖而已;
所以学好了前面的构造函数、原型链更有利于我们理解类的概念和继承关系;
那么,如何使用class来定义一个类呢?
可以使用两种方式来声明类:类声明和类表达式;
javascript
// ES5中定义类
// function Person() {}
// ES6定义类
// {key: value} -> 对象
// {表达式} -> 代码块
// {} -> 类的结构
class Person {
}
// 创建实例对象
var p1 = new Person()
var p2 = new Person()
console.log(p1, p2)
// 另外一种定义方法: 表达式写法(了解, 少用)
var Student = class {
}
var foo = function() {
}
var stu1 = new Student()
console.log(stu1)类的构造函数
如果我们希望在创建对象的时候给类传递一些参数,这个时候应该如何做呢?
每个类都可以有一个自己的构造函数(方法),这个方法的名称是固定的constructor;
当我们通过new操作符,操作一个类的时候会调用这个类的构造函数constructor;
每个类只能有一个构造函数,如果包含多个构造函数,那么会抛出异常;
当我们通过new关键字操作类的时候,会调用这个constructor函数,并且执行如下操作:
1.在内存中创建一个新的对象(空对象);
2.这个对象内部的[[prototype]]属性会被赋值为该类的prototype属性;
3.构造函数内部的this,会指向创建出来的新对象;
4.执行构造函数的内部代码(函数体代码);
5.如果构造函数没有返回非空对象,则返回创建出来的新对象;
javascript
// 编程: 高内聚低耦合
class Person {
// 1.类中的构造函数
// 当我们通过new关键字调用一个Person类时, 默认调用class中的constructor方法
constructor(name, age) {
this.name = name
this.age = age
}
// 2.实例方法
// 本质上是放在Person.prototype
running() {
console.log(this.name + " running~")
}
eating() {
console.log(this.name + " eating~")
}
}
// 创建实例对象
var p1 = new Person("why", 18)
// 使用实例对象中属性和方法
console.log(p1.name, p1.age)
p1.running()
p1.eating()
// 研究内容
console.log(Person.prototype === p1.__proto__) // true
console.log(Person.running) // undefined
console.log(Person.prototype.running)类的实例方法
在上面我们定义的属性都是直接放到了this上,也就意味着它是放到了创建出来的新对象中:
在前面我们说过对于实例的方法,我们是希望放到原型上的,这样可以被多个实例来共享;
这个时候我们可以直接在类中定义;
类和构造函数的异同
我们来研究一下类的一些特性:
你会发现它和我们的构造函数的特性其实是一致的;
javascript
// function定义类
function Person1(name, age) {
this.name = name
this.age = age
}
Person1.prototype.running = function() {}
Person1.prototype.eating = function() {}
var p1 = new Person1("why", 18)
console.log(p1.__proto__ === Person1.prototype)
console.log(Person1.prototype.constructor)
console.log(typeof Person1) // function
// 不同点: 作为普通函数去调用
Person1("abc", 100)
// class定义类
class Person2 {
constructor(name, age) {
this.name = name
this.age = age
}
running() {}
eating() {}
}
var p2 = new Person2("kobe", 30)
console.log(p2.__proto__ === Person2.prototype) // true
console.log(Person2.prototype.constructor) // [class Person2]
console.log(typeof Person2) // function
// 不同点: class定义的类, 不能作为一个普通的函数进行调用
Person2("cba", 0)类的访问器方法
我们之前讲对象的属性描述符时有讲过对象可以添加setter和getter函数的,那么类也是可以的:
javascript
// 针对对象
// 方式一: 描述符
// var obj = {
// _name: "why"
// }
// Object.defineProperty(obj, "name", {
// configurable: true,
// enumerable: true,
// set: function() {
// },
// get: function() {
// }
// })
// 方式二: 直接在对象定义访问器
// 监听_name什么时候被访问, 什么设置新的值
var obj = {
_name: "why",
// setter方法
set name(value) {
this._name = value
},
// getter方法
get name() {
return this._name
}
}
obj.name = "kobe"
console.log(obj.name)javascript
// 1.访问器的编写方式
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 = "kobe"
console.log(p1.name)
// console.log(p1._name)
var p2 = new Person("james", 25)
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关键字来定义:
javascript
// function Person() {}
// // 实例方法
// Person.prototype.running = function() {}
// // 类方法
// Person.randomPerson = function() {}
// var p1 = new Person()
// p1.running()
// Person.randomPerson()
// class定义的类
var names = ["abc", "cba", "nba", "mba"]
class Person {
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)) // 这里用new this,有一天类名改了不用跟着改
}
}
var p1 = new Person()
p1.running()
p1.eating()
var randomPerson = Person.randomPerson()
console.log(randomPerson)ES6类的继承 - extends
前面我们花了很大的篇幅讨论了在ES5中实现继承的方案,虽然最终实现了相对满意的继承机制,但是过程却依然是非常繁琐的。
在ES6中新增了使用extends关键字,可以方便的帮助我们实现继承:
javascript
// 定义父类
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) {
// this.name = name
// this.age = age
super(name, age)
this.sno = sno
this.score = score
}
// running() {
// console.log("running~")
// }
// eating() {
// console.log("eating~")
// }
studying() {
console.log("studying~")
}
}
var stu1 = new Student("why", 18, 111, 100)
stu1.running()
stu1.eating()
stu1.studying()
class Teacher extends Person {
constructor(name, age, title) {
// this.name = name
// this.age = age
super(name, age)
this.title = title
}
// running() {
// console.log("running~")
// }
// eating() {
// console.log("eating~")
// }
teaching() {
console.log("teaching~")
}
}super关键字
我们会发现在上面的代码中我使用了一个super关键字,这个super关键字有不同的使用方式:
注意:在子(派生)类的构造函数中使用this或者返回默认对象之前,必须先通过super调用父类的构造函数!
super的使用位置有三个:子类的构造函数、实例方法、静态方法;
子类的构造函数上面已经使用过了。对父类的实例方法和静态方法部门满意,那么可以在子类调用super,然后拓展一些自己的代码。
javascript
class Animal {
running() {
console.log("running")
}
eating() {
console.log("eating")
}
static sleep() {
console.log("static animal sleep")
}
}
class Dog extends Animal {
// 子类如果对于父类的方法实现不满意(继承过来的方法)
// 重新实现称之为重写(父类方法的重写)
running() {
console.log("dog四条腿")
// 调用父类的方法
super.running()
// console.log("running~")
// console.log("dog四条腿running~")
}
static sleep() {
console.log("趴着")
super.sleep()
}
}
var dog = new Dog()
dog.running()
dog.eating()
Dog.sleep()继承内置类
我们也可以让我们的类继承自内置类,比如Array:
javascript
// 1.创建一个新的类, 继承自Array进行扩展
class HYArray extends Array {
get lastItem() {
return this[this.length - 1]
}
get firstItem() {
return this[0]
}
}
var arr = new HYArray(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(10, 20, 30)
console.log(arr.__proto__ === Array.prototype)
console.log(arr.lastItem())
// 函数apply/call/bind方法 -> Function.prototype类的混入
JavaScript的类只支持单继承:也就是只能有一个父类
那么在开发中我们需要在一个类中添加更多相似的功能时,应该如何来做呢?
这个时候我们可以使用混入(mixin)
javascript
// 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()ES6中的class转ES5代码
可以通过babeljs.io在线网站进行转换
javascript
class Person {
constructor(name, age) {
this.name = name
this.age = age
}
running() {}
eating() {}
static randomPerson() {}
}
var p1 = new Person()转ES5之后
javascript
"use strict";
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
// 实例方法
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
// 类方法
if (staticProps) _defineProperties(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", { writable: false });
return Constructor;
}
// 纯函数: 相同输入一定产生相同的输出, 并且不会产生副作用
var Person = /*#__PURE__*/ (function () {
debugger
function Person(name, age) {
_classCallCheck(this, Person);
this.name = name;
this.age = age;
}
// 这一步本质上就是Person.prototype.running = function() {},只不过是通过属性描述符来实现
// Object.defineProperty(Person.prototype, "running", function running() {})
// Person.prototype.eating = function() {}
// Person.randomPerson = function() {}
// Object.defineProperty(Person, "randomPerson", function randomPerson() {})
_createClass(
Person,
[
{
key: "running",
value: function running() {}
},
{
key: "eating",
value: function eating() {}
}
],
[
{
key: "randomPerson",
value: function randomPerson() {}
}
]
);
return Person;
})();
var p1 = new Person("why", 18)ES6中的extends转ES5代码
javascript
class Person {
constructor(name, age) {
this.name = name
this.age = age
}
running() {}
eating() {}
static randomPerson() {}
}
class Student extends Person {
constructor(name, age, sno, score) {
super(name, age)
this.sno = sno
this.score = score
}
studying() {}
static randomStudent() {}
}
var stu = new Student()转ES5之后
javascript
"use strict";
function _typeof(obj) {
"@babel/helpers - typeof";
return (
(_typeof =
"function" == typeof Symbol && "symbol" == typeof Symbol.iterator
? function (obj) {
return typeof obj;
}
: function (obj) {
return obj &&
"function" == typeof Symbol &&
obj.constructor === Symbol &&
obj !== Symbol.prototype
? "symbol"
: typeof obj;
}),
_typeof(obj)
);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
// SubType.prototype = Object.create(SuperType.prototype)
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: { value: subClass, writable: true, configurable: true }
});
Object.defineProperty(subClass, "prototype", { writable: false });
// 这一步是让子类的__proto__指向父类的构造函数,可以实现构造函数方法的继承
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf
? Object.setPrototypeOf.bind()
: function _setPrototypeOf(o, p) {
// Student.__proto__ = Person
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _createSuper(Derived) { // Derived这里是Student
var hasNativeReflectConstruct = _isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = _getPrototypeOf(Derived), // 返回Derived.__proto__也就是Student.__proto__ = Person
result;
if (hasNativeReflectConstruct) {
var NewTarget = _getPrototypeOf(this).constructor;
result = Reflect.construct(Super, arguments, NewTarget);
} else {
result = Super.apply(this, arguments);
}
return _possibleConstructorReturn(this, result);
};
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
} else if (call !== void 0) {
throw new TypeError(
"Derived constructors may only return object or undefined"
);
}
return _assertThisInitialized(self);
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError(
"this hasn't been initialised - super() hasn't been called"
);
}
return self;
}
function _isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(
Reflect.construct(Boolean, [], function () {})
);
return true;
} catch (e) {
return false;
}
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf
? Object.getPrototypeOf.bind()
: function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", { writable: false });
return Constructor;
}
var Person = /*#__PURE__*/ (function () {
function Person(name, age) {
_classCallCheck(this, Person);
this.name = name;
this.age = age;
}
_createClass(
Person,
[
{
key: "running",
value: function running() {}
},
{
key: "eating",
value: function eating() {}
}
],
[
{
key: "randomPerson",
value: function randomPerson() {}
}
]
);
return Person;
})();
function inherit(SubType, SuperType) {
SubType.prototype = Object.create(SuperType.prototype)
SubType.prototype.constructor = SubType
}
debugger
var Student = /*#__PURE__*/ (function (_Person) {
// 相当于ES5的原型链继承
_inherits(Student, _Person); // 核心代码
var _super = _createSuper(Student); // 这里会得到Person构造函数
function Student(name, age, sno, score) {
var _this;
_classCallCheck(this, Student);
// 相当于ES5的借用构造函数继承
_this = _super.call(this, name, age); // 核心代码
_this.sno = sno;
_this.score = score;
return _this;
}
_createClass(
Student,
[
{
key: "studying",
value: function studying() {}
}
],
[
{
key: "randomStudent",
value: function randomStudent() {}
}
]
);
return Student;
})(Person); // 这里传入Person是为了保证Student是一个纯函数
var stu = new Student("why", 18, 111, 100);JavaScript中的多态
面向对象的三大特性:封装、继承、多态。
前面两个我们都已经详细解析过了,接下来我们讨论一下JavaScript的多态。
JavaScript有多态吗?
维基百科对多态的定义:多态(英语:polymorphism)指为不同数据类型的实体提供统一的接口,或使用一个单一的符号 来表示多个不同的类型。
非常的抽象,个人的总结:不同的数据类型进行同一个操作,表现出不同的行为,就是多态的体现。
那么从上面的定义来看,JavaScript是一定存在多态的。
javascript
// Java中多态理解
// 继承是多态的前提
// shape形状
class Shape {
getArea() {}
}
class Rectangle extends Shape {
constructor(width, height) {
super() // 这里必须调用super才能使用this
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.必须有父类引用指向子类对象 shape->rect1 shape->c1
*/
function getShapeArea(shape) {
console.log(shape.getArea())
}
getShapeArea(rect1)
getShapeArea(c1)
var obj = {
getArea: function() {
return 10000
}
}
getShapeArea(obj) // 正确的用法
getShapeArea(123) // 有安全隐患javascript
// 多态的表现: JS到处都是多态
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中对象字面量进行了增强
字面量的增强主要包括下面几部分:
属性的简写
方法的简写
计算属性名
javascript
/*
1.属性的增强
2.方法的增强
3.计算属性名的写法
*/
var name = "why"
var age = 18
var key = "address" + " city"
var obj = {
// 1.属性的增强
name,
age,
// 2.方法的增强
running: function() {
console.log(this)
},
swimming() {
console.log(this)
},
eating: () => {
console.log(this)
},
// 3.计算属性名
[key]: "广州"
}
obj.running()
obj.swimming()
obj.eating()
function foo() {
var message = "Hello World"
var info = "my name is why"
return { message, info }
}
var result = foo()
console.log(result.message, result.info)解构Destructuring
ES6中新增了一个从数组或对象中方便获取数据的方法,称之为解构Destructuring。
我们可以划分为:数组的解构和对象的解构。
数组的解构:
基本解构过程
顺序解构
解构出数组
默认值
对象的解构:
基本解构过程
任意顺序
重命名
默认值
javascript
var names = ["abc", "cba", undefined, "nba", "mba"]
// 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 obj = { name: "why", age: 18, height: 1.88 }
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(wName, wAge, wHeight)
// 2.4. 默认值
var {
height: wHeight,
name: wName,
age: wAge,
address: wAddress = "中国"
} = obj
console.log(wName, wAge, wHeight, wAddress)
// 2.5. 对象的剩余内容
var {
name,
age,
...newObj
} = obj
console.log(newObj)
// 应用: 在函数中(其他类似的地方)
function getPosition({ x, y }) {
console.log(x, y)
}
getPosition({ x: 10, y: 20 })
getPosition({ x: 25, y: 35 })
function foo(num) {}
foo(123)函数的对象原型关系回顾
javascript
// new Function()
// foo.__proto__ === Function.prototype
function foo(name, age) {
console.log(this, name, age)
}
// 1.对象中的某些属性和方法是来自Function.prototype
// test.__proto__ === Function.prototype
function test() {}
// foo当做一个对象, 获取apply方法
// foo.apply("abc", ["why", 18])
// console.log(Function.prototype.call)
// console.log(Function.prototype.apply)
// console.log(Function.prototype.apply === foo.apply)
// 2.在Function.prototype中添加的属性和方法, 可以被所有的函数获取
Function.prototype.info = "hello why"
console.log(test.info)
console.log(foo.info)
Function.prototype.bar = function() {
console.log("bar function execution")
}
test.bar()
foo.bar()
// Array.prototype.slice.apply(arguments);
// [].slice.apply(arguments)手写apply-call函数
javascript
// new Function()
// foo.__proto__ === Function.prototype
function foo(name, age) {
console.log(this, name, age)
}
// foo函数可以通过apply/call
// foo.apply("aaa", ["why", 18])
// foo.call("bbb", "kobe", 30)
// 1.给函数对象添加方法: hyapply
Function.prototype.hyapply = function(thisArg, otherArgs) {
// this -> 调用的函数对象
// thisArg -> 传入的第一个参数, 要绑定的this
// console.log(this) // -> 当前调用的函数对象
// this.apply(thisArg)
thisArg.fn = this
// 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(...otherArgs)
delete thisArg.fn
}
// foo.hyapply({ name: "why" }, ["james", 25])
// foo.hyapply(123, ["why", 18])
// foo.hyapply(null, ["kobe", 30])
// 2.给函数对象添加方法: hycall
Function.prototype.hycall = function(thisArg, ...otherArgs) {
// 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(...otherArgs)
delete thisArg.fn
}
foo.hycall({ name: "why", fn: "abc" }, "james", 25)
foo.hycall(123, "why", 18)
foo.hycall(null, "kobe", 30)手写apply-call抽取封装
javascript
// new Function()
// foo.__proto__ === Function.prototype
function foo(name, age) {
console.log(this, name, age)
}
// foo函数可以通过apply/call
// foo.apply("aaa", ["why", 18])
// foo.call("bbb", "kobe", 30)
// 1.封装思想
// 1.1.封装到独立的函数中
function execFn(thisArg, otherArgs, fn) {
// 1.获取thisArg, 并且确保是一个对象类型
thisArg = (thisArg === null || thisArg === undefined)? window: Object(thisArg)
// thisArg.fn = this
Object.defineProperty(thisArg, "fn", {
enumerable: false,
configurable: true,
value: fn
})
// 执行代码
thisArg.fn(...otherArgs)
delete thisArg.fn
}
// 1.2. 封装原型中
Function.prototype.hyexec = function(thisArg, otherArgs) {
// 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(...otherArgs)
delete thisArg.fn
}
// 1.给函数对象添加方法: hyapply
Function.prototype.hyapply = function(thisArg, otherArgs) {
this.hyexec(thisArg, otherArgs)
}
// 2.给函数对象添加方法: hycall
Function.prototype.hycall = function(thisArg, ...otherArgs) {
this.hyexec(thisArg, otherArgs)
}
foo.hyapply({ name: "why" }, ["james", 25])
foo.hyapply(123, ["why", 18])
foo.hyapply(null, ["kobe", 30])
foo.hycall({ name: "why" }, "james", 25)
foo.hycall(123, "why", 18)
foo.hycall(null, "kobe", 30)手写bind函数
javascript
// apply/call
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.88)
// 实现hybind函数
Function.prototype.hybind = 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)
}
}
var newFoo = foo.hybind("abc", "kobe", 30)
newFoo(1.88, "广州市")
newFoo(1.88, "广州市")
newFoo(1.88, "广州市")
newFoo(1.88, "广州市")