关于JS,这两者有什么区别?我知道方法与对象有关,但是混淆了函数的用途是什么?它们的语法有何不同?
另外,这两种语法之间的区别是什么:
var myFirstFunc = function(param) {
//Do something
};
Run Code Online (Sandbox Code Playgroud)
和
function myFirstFunc(param) {
//Do something
};
Run Code Online (Sandbox Code Playgroud)
另外,在使用函数之前,我在某处看到了我们需要做的事情:
obj.myFirstFunc = myFirstFunc;
obj.myFirstFunc("param");
Run Code Online (Sandbox Code Playgroud)
为什么需要第一行,它有什么作用?
对不起,如果这些是基本问题,但我开始使用JS而且很困惑.
编辑:对于最后一点代码,这就是我所说的:
// here we define our method using "this", before we even introduce bob
var setAge = function (newAge) {
this.age = newAge;
};
// now we make bob
var bob = new Object();
bob.age = 30;
// and down here we just use the method we already made
bob.setAge = setAge;
Run Code Online (Sandbox Code Playgroud) 这个问题来源于超级关键字意外
接受的答案是:
因为super只在方法内部有效.
但在MDN中,似乎这两种方法都是:
let person = {
greeting() {
return "Hello";
}
};
let friend = {
// shorter syntax for method?
greeting() {
return super.greeting() + ", hi!";
}
// method?
// greeting: function() {
// return super.greeting() + ", hi!"; // Throw error: Uncaught SyntaxError: 'super' keyword unexpected here
// }
};
Object.setPrototypeOf(friend, person);
console.log(friend.greeting());
Run Code Online (Sandbox Code Playgroud)
在了解es6时,Nacholas说:
尝试
super在简洁方法之外使用会导致语法错误
Methods只是包含函数而不是数据的对象属性.任何引用都
super使用[[HomeObject]]来确定要做什么.第一步是在[[HomeObject]]上调用Object.getPrototypeOf()来检索对原型的引用.然后,在原型中搜索具有相同名称的函数.最后,设置此绑定并调用该方法.
所以似乎[[HomeObject]]在方法的简写语法上有所不同?我很好奇为什么?