关于import的一个疑问
发布于 3 年前 作者 ScarletMoki 2134 次浏览 来自 问答

背景:有个朋友是搞上位机,写C++的,我们用的是基于Qt的JS引擎。 问题:他问我在JavsScript里,require一个模块之后,为什么不能直接用里面的方法。 我的回答: 其实一开始我其实没get到他的意思,讲export,然后又拿死月大佬的《来一打C++扩展》翻了翻,半天鸡同鸭讲。 后来我是这么回答的,在某个模块 require了另个模m块,直接用a() ,其实是用当前模块.prototype.a() 而不是m.a(),JS中的OOP并非是传统的OOP。 想请教一下社区里的各位大佬,node里面的require、import 和C++中的import的区别

5 回复

可以直接用

const http = require("http")
http.get('http://www.baidu.com', (res) => {
  console.log(`Got response: ${res.statusCode}`);
  // consume response body
  res.resume();
}).on('error', (e) => {
  console.log(`Got error: ${e.message}`);
});

@yakczh 类似友元类那样,在直接使用本类没有的方法。比如本模块没有get方法,为什么在require之后不能直接使用get(),而是一定要http.get()

没看懂你想问啥,跟 prototype 啥的没关系。

问题:他问我在JavsScript里,require一个模块之后,为什么不能直接用里面的方法。

答案是:你的模块写的有问题。

空对空聊没啥意义,模块长什么样,如何 require 的,贴出来一个最小可复现仓库,分分钟就能找到问题了。

@ScarletMoki 因为c++ 显式地声明了 using namespace xxx ; 如果客户代码不写using  namespace 一样不能直接调用 而nodejs没有using namespace xxx 这样的语法,所有的package都挂在 exports.xxx 下面, 客户代码直接require 'xxx’ xxx.method 这样比c++更简单明了

#include <iostream>
using namespace std;
namespace square {
	int x=100;
	int y=200;
	void say(char* msg) {
		cout << msg <<endl;
	}
}

namespace round {
	int x=300;
	int y=400;
	void say(char* msg) {
		cout << msg <<endl;
	}
}



int main() {
    //using namespace square;
   // say("square");

    //cout << x << "  " << y << endl;
    using namespace round;
    cout << x << y << endl;
    say("round"); 
}


你不写using namespace  看能调用方法吗?

@yakczh 非常感谢

回到顶部