Javascript 在JS中使对象方法成为变量
比如说,我有一个名为Javascript 在JS中使对象方法成为变量,javascript,Javascript,比如说,我有一个名为Animal的构造函数,它有两个原型方法,foo和bar 我创建一个新对象: const animal = new Animal() 我可以打电话: animal.foo() 或 我可以用另一种方法(baz)替换这两种方法吗 比如: 因此,根据上下文,我想将foo或bar分配给baz面向对象的方法是创建两个子类,每个上下文一个子类。在每一种方法中,您都将定义baz方法,分别将其参数传递给this.foo或this.bar 您还可以使用animal.baz=animal.在
Animal
的构造函数,它有两个原型方法,foo
和bar
我创建一个新对象:
const animal = new Animal()
我可以打电话:
animal.foo()
或
我可以用另一种方法(baz
)替换这两种方法吗
比如:
因此,根据上下文,我想将
foo
或bar
分配给baz
面向对象的方法是创建两个子类,每个上下文一个子类。在每一种方法中,您都将定义baz
方法,分别将其参数传递给this.foo
或this.bar
您还可以使用
animal.baz=animal.
在对象上动态定义baz
。但是,该策略的可维护性较差(每次实例化对象时都必须定义该策略),性能较差(解释器针对具有不变属性的对象进行了优化)。在不知道上下文的形式的情况下,一种简单的方法是传递上下文(以任何形式)在构造函数中,将其存储在对象中,当调用baz
时,检查存储的上下文并相应地执行操作。这也是非常灵活的:
// ES6
class Animal {
constructor(context) {
this.context = context;
}
foo() {
...
}
bar() {
...
}
baz() {
if(context == "some string id maybe?") {
return this.foo();
} else if(context == 13523) { // some integer id
return this.foo();
} else if(context === someContextObject) { // some context object
return this.bar();
} else {
return this.foo();
}
}
}
//Vanilla
const Animal = function(context) {
this.context = context;
}
Animal.prototype.foo = function() {
...
}
Animal.prototype.bar = function() {
...
}
Animal.prototype.baz = function() {
if(context == "some string id maybe?") {
return this.foo();
} else if(context == 13523) { // some integer id
return this.foo();
} else if(context === someContextObject) { // some context object
return this.bar();
} else {
return this.foo();
}
}
像这样的D
类动物{
构造函数(IsAggressive){
this.seesMe=isaggressive?this.attack:this.fleed;
}
攻击=功能(){
console.log('attack!');
}
逃走{
console.log('cya!');
}
}
const斑马=新动物(假);
const lion=新动物(正确);
斑马;
狮子(seesMe()代码>您要检查的上下文是什么?它是某个对象的类、对象、字符串/数字id吗?是的,可以。“但是为什么呢?”尼纳斯科尔斯只是好奇。
animal.baz()
// ES6
class Animal {
constructor(context) {
this.context = context;
}
foo() {
...
}
bar() {
...
}
baz() {
if(context == "some string id maybe?") {
return this.foo();
} else if(context == 13523) { // some integer id
return this.foo();
} else if(context === someContextObject) { // some context object
return this.bar();
} else {
return this.foo();
}
}
}
//Vanilla
const Animal = function(context) {
this.context = context;
}
Animal.prototype.foo = function() {
...
}
Animal.prototype.bar = function() {
...
}
Animal.prototype.baz = function() {
if(context == "some string id maybe?") {
return this.foo();
} else if(context == 13523) { // some integer id
return this.foo();
} else if(context === someContextObject) { // some context object
return this.bar();
} else {
return this.foo();
}
}