JavaScript闭包上下文的其他属性发生了什么

What happens with the other properties of a JavaScript closure context ?

本文关键字:属性 发生了 什么 其他 闭包 上下文 JavaScript      更新时间:2023-09-26

我会尽可能清楚地说明我的问题,所以:

有很多博客和教程解释闭包,但我没有设法弄清楚的是,从闭包得到创建的上下文的其他属性发生了什么?jsFiddle

function func(){
    this.context_field = "context_field";
    this.context_method = function(){
        console.log("context method");
    };

    func = function(param, change){
        if(typeof(change) === 'undefined'){
           //......
            console.log(param + " " + context_field + " from original func - closure'n'n");
           //.....
    }
    return func;
};
func()("Init finished and call");
func("Call again", "");

在这个例子中,没有创建上下文,因为函数'func'内部的关键字'this'指的是window(全局对象)。

要创建一个上下文,像这样声明变量:

var context_field = "context_field";
var context_method = function(){
    console.log("context method");
};

因此,创建闭包的上下文的其他属性是活的,可以在闭包内部调用,但要使它们在外部可用,唯一的方法是返回它们。

function func(){
    var context_field = "context_field";
    var context_method = function(){
        console.log("context method lives on");
    };
    func = function(param){
        console.log(param + " func and " + context_field);
        return context_method;
    }
    return func;
};
func()("Init finished and call");
func("Call again")();