如何使用闭包的apply/call通过嵌套对象传递变量

How do you pass variables through nested objects using apply/call for closures

本文关键字:嵌套 对象 变量 call 闭包 何使用 apply      更新时间:2023-09-26

即使在阅读了网站和SO上的教程之后,我也无法理解call/apply如何工作。我了解基本的机制,直到事情变得嵌套。如果不依赖that = this,我该如何使用call函数来代替闭包呢?

var createPerson = function () {
    var that = this;
    var name;
    return {
        bio: {
            name: function (name) {
                that.name = name;
            }
        },
        getInfo: {
            getName: function () {
                return that.name;
            }
        }
    }
}
var john = createPerson();
john.bio.name("Johnathan");
console.log(john.getInfo.getName());

你所要做的就是在你的函数上使用this,并在返回的对象上使用call

var createPerson = function () {
    return {
        bio: {
            name: function (name) {
                this.name = name;
            }
        },
        getInfo: {
            getName: function () {
                return this.name;
            }
        }
    }
}
var john = createPerson();
john.bio.name.call(john, 'Jonathan');
console.log(person.getInfo.getName.call(john));

Function.prototype.call将调用您的函数,johnthis

Function.prototype.bind示例:

var createPerson = function () {
    var person = {
        bio: {},
        getInfo: {}
    };
    person.bio.name = Function.bind.call(function (name) {
        this.name = name;
    }, person);
    person.getInfo.getName = Function.bind.call(function () {
        return this.name;
    }, person);
    return person;
}
var john = createPerson();
john.bio.name("Johnathan");
console.log(john.getInfo.getName());

请注意,您可以很容易地将它替换为:

var createPerson = function () {
    var person = {
        bio: {},
        getInfo: {}
    };
    person.bio.name = function (name) {
        person.name = name;
    }
    person.getInfo.getName = function () {
        return person.name;
    }
    return person;
}
var john = createPerson();
john.bio.name("Johnathan");
console.log(john.getInfo.getName());