如何通过call和apply方法实现长尾词的灵活调用?
- 内容介绍
- 文章标签
- 相关推荐
本文共计351个文字,预计阅读时间需要2分钟。
`JavaScript 中 Function.prototype 的 call 和 apply 方法及其应用场景:1. 调用函数;2. 将类数组对象转换为数组对象;3. 使用他人的方法;4. 绑定 this 的指向;5. 继承;6. 实现 ES6 扩展运算符功能。`
/* call和apply位于Function.prototype上,使用场景: 1、调用函数 2、将类数组对象转化成数组对象 3、借用别人的方法 4、绑定this的指向 5、继承 6、实现ES6扩展运算符功能 */ function foo() { console.log(this === window); } foo(); // true foo.call(); // true foo.apply(); // true /*非严格模式下*/ foo.call(null); // true foo.call(undefined); // true // 2、将类数组对象转化成数组对象 function person(name, age, high) { console.log(arguments); var arr = [].slice.apply(arguments); console.log(arr); } person('xiaoming', 12, '1.6m'); // 3、借用别人的方法 var arr = [1, 2, 3, 4, 5, 6]; Math.max.call(Math, arr); // 6 // 4、绑定this的指向 var foo = { name: 'foo', showName: function () { console.log(this.name); } } var bar = { name: 'bar' } foo.showName.apply(bar); // 'bar' // 5、继承 var Father = function (name, age, high) { this.name = name; this.age = age; } var Student = function (name, age, high) { // 继承父类,调用父类构造函数 // 此处this指向Student对象实例 Father.call(this, name, age, high); this.high = high; } Student.prototype.message = function () { // 此处this指向Student对象实例 console.log("name: " + this.name + ",age: " + this.age + ",high: " + this.high); } new Student('xiaoming', 12, '1.6').message(); // 6、实现ES6扩展运算符功能 // console.log打印会拍平数组 (_console = console).log.apply(_console, [1, 2, 3]); // 1 2 3 // 只有Function才有prototype,包括new Object()也是根据传参调用具体的Function构造函数
本文共计351个文字,预计阅读时间需要2分钟。
`JavaScript 中 Function.prototype 的 call 和 apply 方法及其应用场景:1. 调用函数;2. 将类数组对象转换为数组对象;3. 使用他人的方法;4. 绑定 this 的指向;5. 继承;6. 实现 ES6 扩展运算符功能。`
/* call和apply位于Function.prototype上,使用场景: 1、调用函数 2、将类数组对象转化成数组对象 3、借用别人的方法 4、绑定this的指向 5、继承 6、实现ES6扩展运算符功能 */ function foo() { console.log(this === window); } foo(); // true foo.call(); // true foo.apply(); // true /*非严格模式下*/ foo.call(null); // true foo.call(undefined); // true // 2、将类数组对象转化成数组对象 function person(name, age, high) { console.log(arguments); var arr = [].slice.apply(arguments); console.log(arr); } person('xiaoming', 12, '1.6m'); // 3、借用别人的方法 var arr = [1, 2, 3, 4, 5, 6]; Math.max.call(Math, arr); // 6 // 4、绑定this的指向 var foo = { name: 'foo', showName: function () { console.log(this.name); } } var bar = { name: 'bar' } foo.showName.apply(bar); // 'bar' // 5、继承 var Father = function (name, age, high) { this.name = name; this.age = age; } var Student = function (name, age, high) { // 继承父类,调用父类构造函数 // 此处this指向Student对象实例 Father.call(this, name, age, high); this.high = high; } Student.prototype.message = function () { // 此处this指向Student对象实例 console.log("name: " + this.name + ",age: " + this.age + ",high: " + this.high); } new Student('xiaoming', 12, '1.6').message(); // 6、实现ES6扩展运算符功能 // console.log打印会拍平数组 (_console = console).log.apply(_console, [1, 2, 3]); // 1 2 3 // 只有Function才有prototype,包括new Object()也是根据传参调用具体的Function构造函数

