JavaScript新手求助:如何正确编写可直接调用的库方法?
问题
我是JavaScript新手,正尝试为自己编写一个库,避免后续重复编码。我编写了如下代码:
function lib() { let _this = this; this.addstring= (n, d) => { return n + d } } console.log(lib.addstring("foo", "bar"))
运行该代码时,提示lib.addstring is not a function,请问该如何正确编写这个方法?
问题已由@traynor在评论区解答
解决方法
你当前的代码把addstring定义成了实例方法(挂载在构造函数的this上),这类方法只能通过构造函数创建的实例来调用,直接用构造函数lib调用自然会报错。下面提供几种可行的修改方式:
1. 创建实例后调用方法
先通过new关键字生成lib的实例,再调用实例上的方法:
function lib() { this.addstring = (n, d) => { return n + d } } const myLib = new lib(); console.log(myLib.addstring("foo", "bar")); // 输出 "foobar"
2. 定义为静态方法
如果想直接通过lib.addstring调用,把方法挂载在构造函数本身即可:
function lib() { let _this = this; } lib.addstring = (n, d) => { return n + d } console.log(lib.addstring("foo", "bar")); // 输出 "foobar"
3. 原型链定义实例方法(推荐扩展场景)
如果后续要添加更多实例方法,用原型链定义能避免每次创建实例都重复生成函数,更节省内存:
function lib() {} lib.prototype.addstring = function(n, d) { return n + d } const myLib = new lib(); console.log(myLib.addstring("foo", "bar")); // 输出 "foobar"
内容的提问来源于stack exchange,提问作者bmp
相关产品推荐
相关产品推荐

