Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
76 views
in Technique[技术] by (71.8m points)

javascript - How to inject custom function to class in typescript

I would like to inject a custom function into my class from variable functions, how can I do this?

My code is:

const functions = {
    foo: () => console.log('foo') 
}

class ParentBase {
    parentHello() {
        console.log('parentHello')
    }
}

function Base() {
    class BaseClass extends ParentBase { }
    BaseClass.foo = functions['foo']
    return BaseClass;
} 

const Class = Base();
const instance = new Class(); 

instance.parentHello() // it work
instance.foo() // foo  is not a function 

question from:https://stackoverflow.com/questions/65843644/how-to-inject-custom-function-to-class-in-typescript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could directly declare a new method in the class declaration:

class BaseClass extends ParentBase { 
  foo() {functions["foo"](); }
}

If the method name should be dynamic, you can also use computed method names:

class BaseClass extends ParentBase { 
  [window.location]() {functions["foo"](); }
}

If you really want to "dynamically inject" a new method (e.g. conditionally, in a loop, or some other strange construct), you'd have to write into BaseClass.prototype, which is the object BaseClass instances will inherit from:

BaseClass.prototype.foo = functions["foo"];

This will however be an enumerable property, to create a non enumerable one, use Object.defineProperty:

Object.defineProperty(BaseClass.prototype, "foo", {
  value: functions["foo"],
  /* enumerable: false,
     writable: false */
});

Here is a small showcase:

class ParentBase {
    parentHello() {
        console.log('parentHello')
    }
}

function Base() {
    class BaseClass extends ParentBase {
      instanceMethod() { console.log("BaseClass.prototoype.test", this); };
      static classMethod() { console.log("BaseClass.classMethod", this); };
    }
    BaseClass.classMethod2 = function() { console.log("BaseClass.classMethod2", this); };
    BaseClass.prototype.instanceMethod2 = function() { console.log("BaseClass.prototype.instanceMethod2", this); };
    Object.defineProperty(BaseClass.prototype, "instanceMethod3", { value() { console.log("BaseClass.prototype.instanceMethod3", this); } });
    
    return BaseClass;
} 

const Class = Base();
const instance = new Class();

Class.classMethod();
Class.classMethod2();

instance.instanceMethod();
instance.instanceMethod2();
instance.instanceMethod3();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...