标签:null 模拟 fine class 占用 完成 总结 app js字符串
function sayName(age) { // this.name = "person"; (1) console.log(this.name,age); } const student = { name: "student" }; sayName.call(student,12); //person 12 (1) sayName.call(student,13); //student 13 // call的作用: call 改变了 this 的指向,指向到 student //(1)假如函数内部有相同属性情况,引用函数内部的属性
const student = { name: "student”, sayName:function(age){ console.log(this.name,age); } }; student.sayName(12); //person 12 (1)
// 第一版 Function.prototype.callSub = function(context) { context.fn = this; context.fn(); delete context.fn; }; sayName.callSub(student); //student
// 第二版 Function.prototype.callSub = function(context) { context.fn = this; let args = []; for (var i = 1; i < arguments.length; i++) { // 需要从第二个参数开始 args.push(arguments[i]); } var result = context.fn(...args); delete context.fn; return result; }; function sayName(age, name) { return { age: age, name: name }; } const student = { name: "小红" }; console.log(sayName.callSub(student, 12, "小明")); //{age: 12, name: "小明"}
// 最终版 Function.prototype.callSub = function(context) { var context = context || window; // 当context为null 的时候指向window context.fn = this; let args = []; for (var i = 1; i < arguments.length; i++) { // 需要从第二个参数开始 args.push("arguments[" + i + "]"); } var result = eval("context.fn(" + args + ")"); delete context.fn; return result; }; function sayName(age, name) { return { age: age, name: name, gender:this.gender }; } const student = { name: "小红", gender:"woman" }; console.log(sayName.callSub(student, 12, "小明")); //{age: 12, name: "小明", gender: "woman”} function sayHello() { console.log("hello"); } sayHello.callSub(); // hello
// apply接受的参数是一个数组 Function.prototype.applySub = function(context, arr) { var context = context || window; context.fn = this; var result; if (!arr) { result = context.fn(); } else { var args = []; for (var i = 0; i < arr.length; i++) { args.push("arr[" + i + "]"); } result = eval("context.fn(" + args + ")"); } delete context.fn; return result; }; function sayName(age, name) { return { age: age, name: name, gender: this.gender }; } const student = { name: "小红", gender: "woman" }; console.log(sayName.applySub(student, [12, "小明"])); //{age: 12, name: "小明",gender:"woman"} function sayHello() { console.log("hello"); } sayHello.applySub(); // hello
理解javascript中call/apply的使用和模拟实现
标签:null 模拟 fine class 占用 完成 总结 app js字符串
原文地址:https://www.cnblogs.com/chrissong/p/10493577.html