如何在函数外部访问JavaScript函数参数? [英] How can I access JavaScript function argument outside the function?

查看:54
本文介绍了如何在函数外部访问JavaScript函数参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在函数外部访问函数参数吗?

Can I access the function arguments outside the function?

这是我的代码:

function viewmessage(username,name) {
        //alert(name + " : " + username);
        $('#heading').html(name);
        $.get('/notification/viewmessage', {user:username}, function(data) {
            $('#messagesfrom').html(data);
            $('#newmessage').slideDown(200);
        });
    }
alert(name + " : " + username);

推荐答案

除非您在函数外部声明了变量,否则您将无法这样做.

You can't, unless you declare the variable outside the function.

您只能在全局范围内使用相同的变量名称:

You can only use the same variable names in the global scope:

function viewmessage(username, name){
    window.username = username;
    window.name = name;
}
alert(window.name + " : " + window.username ); // "undefined : undefined"
alert(name+" : "+username); // ReferenceError: 'name' not defined

在本地范围内,必须使用在函数内部重新声明的变量名称:

In a local scope, you have to use variable names which are re-declared inside the function:

var username2, name2;
function viewmessage(username, name){
    username2 = username; // No "var"!!
    name2 = name;
}
alert(username2 + " : " + name2); // "undefined : undefined"
viewmessage('test', 'test2');
alert(username2 + " : " + name2); // "test : test2"

这篇关于如何在函数外部访问JavaScript函数参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆