Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/397.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使函数使用对象作为其作用域_Javascript_Object_Scope - Fatal编程技术网

Javascript 使函数使用对象作为其作用域

Javascript 使函数使用对象作为其作用域,javascript,object,scope,Javascript,Object,Scope,假设我有这样的代码: var opts = {hello: "it's me", imusthavetried: "a thousand times"} function myFunction (options) { } myFunction(opts) 有没有办法让myFunction只写hello而不是选项。hello?我知道我可以循环遍历每个选项对象子对象并重新定义它们,但有没有办法自动将选项对象用作函数的作用域?您可以使用块,但通常不赞成使用它(如中所述)。过去,这会导致性能问题,但在

假设我有这样的代码:

var opts = {hello: "it's me", imusthavetried: "a thousand times"}
function myFunction (options) {
}
myFunction(opts)
有没有办法让
myFunction
只写
hello
而不是
选项。hello
?我知道我可以循环遍历每个选项对象子对象并重新定义它们,但有没有办法自动将选项对象用作函数的作用域?

您可以使用块,但通常不赞成使用它(如中所述)。过去,这会导致性能问题,但在现代版本的V8引擎(Google Chrome和Node.js使用的引擎)中已经解决了这一问题

函数myFunction(选项){
带(选项){
console.log(hello);
}
}
myFunction({hello:'hello,World!'})您可以使用块,但通常不赞成使用它(如中所述)。过去,这会导致性能问题,但在现代版本的V8引擎(Google Chrome和Node.js使用的引擎)中已经解决了这一问题

函数myFunction(选项){
带(选项){
console.log(hello);
}
}

myFunction({hello:'hello,World!'})另一种选择是将“this”对象绑定到您的对象:

var opts={你好:“是我”,我必须尝试:“一千次”}
函数myFunction(选项){
console.log(this.hello)
}
myFunction=myFunction.bind(opts);

myFunction()另一种选择是将“this”对象绑定到您的对象:

var opts={你好:“是我”,我必须尝试:“一千次”}
函数myFunction(选项){
console.log(this.hello)
}
myFunction=myFunction.bind(opts);

myFunction()
你说的“可以直接写hello而不是options.hello”是什么意思?
带有(options){alert(hello);}
你是说在
myFunction
中执行
console.log(options['hello'])
?这应该记录“是我”
@VincentNguyen不,@NiettheDarkAbsol回答了我的问题。我的意思是你可以只做
console.log(hello)
而不必写
options
或者显式地给
hello
@NiettheDarkAbsol赋值,但是如果
hello
是在外部定义的,它会返回那个值,对吗?你所说的“可以直接写hello而不是options.hello”是什么意思{alert(hello);}
你的意思是在
myFunction
中执行
console.log(选项['hello'])
?这应该记录
'it me'
@VincentNguyen不,@NiettheDarkAbsol回答了我的问题。我的意思是你可以执行
console.log(hello)
根本不写
选项,也不显式地给
hello
@NiettheDarkAbsol赋值,但如果
hello
是外部定义的,它会返回该值,对吗?在“使用:严格”中是否禁用了该值?另外,如果
hello
是外部定义的,它会不会使用
hello
而不是
选项。hello
?@BenGubler是的,它在严格模式下被禁用。不,它总是更喜欢使用
选项。hello
。有没有与严格模式一起工作的等价物?@BenGubler在严格模式下没有等价物。它被禁用了吗n“使用:严格”?另外,如果
hello
是外部定义的,它会使用
hello
而不是
选项吗?hello
?@BenGubler是的,它在严格模式下被禁用。不,它总是更喜欢使用
选项。hello
。有任何等价物可以在严格模式下工作吗?@BenGubler在严格模式下没有等价物。
var opts = {hello: "it's me", imusthavetried: "a thousand times"}
function myFunction (options) {
    with( options ) {
        console.log( hello ); // "it's me"
    }
}
myFunction(opts)