我对javascript很陌生(新生),我们得到了这个
function invokeMethod(object, method) {
// method is a string that contains the name of a method on the object
// invoke this method
// nothing needs to be returned
我试过这个
const obj = {
'name': function(){
this.name = method;
}
}
obj = object;
obj.name();
我尝试测试它,但它失败了。它说 obj 是未定义的。如何以及在何处声明已作为参数传递的对象?请帮助我卡了几个小时。谷歌无能为力,或者我搜索了一个错误。谢谢
欢迎来到 StackOverflow!请在回答前阅读作业
function invokeMethod(object, method) {
// method is a string that contains the name of a method on the object
// invoke this method
// nothing needs to be returned
// The assignment ask you to call (invoke) the method inside of `object`
// The function can be retrieved by using `object[method]`
// Then, you can call them as you wish, like so:
object[method](); // This will invoke the method inside of `object`
}
"已作为参数传递的对象">
object
参数尚未传递,您在函数中看到的只是参数的名称。调用函数时,您必须自己传递对象(就像调用任何其他函数一样,例如Math.sin(1.234)
)。参数是位置的,在函数之外,参数的名称无关紧要(名称不必匹配)。因此,您只需创建一个对象,为其指定任何名称(假设它是obj
),然后调用:
invokeMethod(obj, ...);
在函数内部,名称object
将绑定到(引用)obj
,即您传入的内容。它本质上是函数持续时间的别名(也就是说,它们都引用同一个对象)。
你写道:
const obj = {
'name': function(){
this.name = method;
}
}
你不必做这些恶作剧。只需正常声明对象:
const obj = {
sayHello: function() {
console.log('Hi!');
}
}
在 JavaScript 中,对象有点像字典,因此它们上的每个属性都已经存储为字符串键。你可以像这样调用sayHello函数:
obj.sayHello();
或像这样(不经常使用,但它有效)。
obj['sayHello']();
旁白:例如,如果你有
const point = { x: 1, y: 5 }
您可以通过执行
point.x
或执行point['x']
你的赋值希望你传递这个对象和要调用的函数的名称给invokeMethod
函数。同样,你必须自己称呼它;他们希望您通过调用invokeMethod
来间接调用该函数:
invokeMethod(obj, 'sayHello'); // internally, this should call sayHello on obj
完成此操作后,函数将执行,object
参数绑定到obj
,method
参数绑定到"sayHello"
。现在剩下的就是把这些碎片放在一起,填满invokeMethod
函数的主体。