在Javascript中,是否有一种多态设置器的方法
背景:库对象具有一个用于方法的属性,但程序员经常错误地将其作为属性访问-> e、 例如,预期接口:在Javascript中,是否有一种多态设置器的方法,javascript,polymorphism,closures,setter,Javascript,Polymorphism,Closures,Setter,背景:库对象具有一个用于方法的属性,但程序员经常错误地将其作为属性访问-> e、 例如,预期接口: this.filter(function(){...}); 通常被误认为是 this.filter=function(){...}; 当然,这会覆盖该方法。(哎哟) 处理这种情况的第一个尝试是改变现状 this.filter = function(implementation) { this.format = implementation;
this.filter(function(){...});
通常被误认为是
this.filter=function(){...};
当然,这会覆盖该方法。(哎哟)
处理这种情况的第一个尝试是改变现状
this.filter = function(implementation) {
this.format = implementation;
this.isfilter = true;
}
到
这对于错误的用例(this.filter=…)是很好的
但是当然是第一个(预期的情况,this.filter(function(){}))
不能再工作了
在这种情况下,是否存在多态性?我必须同时处理这两件事
情况-a)不清除现有代码,b)1)处理分配或发布错误用例的警告/异常?
或者有什么闭包魔法可以做到这一点吗?这当然可以做到 通过将方法替换为
get
only属性返回函数
使用ES2015类:
class Filterable {
get filter() {
return (implementation) => {
this.format = implementation;
this.isfilter = true;
}
}
}
请注意,缺少属性设置器
尝试分配到此属性将失败,并在严格模式下抛出错误(始终使用严格模式!)
例如:
“严格使用”;
类可过滤{
获取筛选器(){
返回(实现)=>{
this.format=实现;
this.isfilter=true;
}
}
}
常数filterable=新的filterable();
filterable.filter(函数(){});//好啊
filterable.filter=函数(){};//错误
这当然可以做到
通过将方法替换为get
only属性返回函数
使用ES2015类:
class Filterable {
get filter() {
return (implementation) => {
this.format = implementation;
this.isfilter = true;
}
}
}
请注意,缺少属性设置器
尝试分配到此属性将失败,并在严格模式下抛出错误(始终使用严格模式!)
例如:
“严格使用”;
类可过滤{
获取筛选器(){
返回(实现)=>{
this.format=实现;
this.isfilter=true;
}
}
}
常数filterable=新的filterable();
filterable.filter(函数(){});//好啊
filterable.filter=函数(){};//错误
您可以使用Object.freeze(this.filter),不使用多态性,但不允许用户覆盖它。您可以使用Object.freeze(this.filter),不使用多态性,但不允许用户覆盖它。