如何解决新生的 Javascript 对象
我对 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
或通过执行来访问 x 的值
point['x']
您的任务希望您将此对象和函数名称传递给 invokeMethod
函数。同样,您必须自己调用它;他们希望您通过调用 invokeMethod
:
invokeMethod(obj,'sayHello'); // internally,this should call sayHello on obj
执行此操作后,函数将执行,object
参数绑定到 obj
,method
参数绑定到 "sayHello"
。现在剩下的就是将各个部分放在一起并填充 invokeMethod
函数的主体。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。