为什么我们不能像函数声明那样写原型(prototype)函数:
仅允许在函数表达式中使用:
function SinglyLinkedList() {
this.head = null;
this.tail = null;
}
SinglyLinkedList.prototype.add = function(data){
console.log(data);
} // working as expected
function SinglyLinkedList.prototype.add(data){
console.log(data);
}
// showing error.
最佳答案
因为语法不是这样设计的。也许它可以这样设计,但事实并非如此。 function declaration 中的名称(更准确地说,绑定(bind)标识符)必须与 Identifier 的定义匹配,这意味着它不能是像 SinglyLinkedList.prototype.add
这样的属性路径。
请注意,如果您正在寻找更短的内容,您可以使用 Object.assign
(新的,但可填充)和使用方法语法的对象初始值设定项(ES2015 中的新功能):
Object.assign(SinglyLinkedList.prototype, {
add(data) {
console.log(data);
},
remove(/*...*/) {
// ...
}
// etc.
});
或者对于 ES2015 之前的环境(使用 Object.assign
的填充),属性语法而不是方法语法:
Object.assign(SinglyLinkedList.prototype, {
add: function(data) {
console.log(data);
},
remove: function(/*...*/) {
// ...
}
// etc.
});
当然,ES2015+ 有了 class
,它也比旧的方式更简洁。
关于javascript - 无法将原型(prototype)函数编写为 JavaScript 中的函数声明。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48381317/