我喜欢理解 javascript
或特别是 node.js 的 require()
的一种行为。我已经读过这个:
Adding new properties to constructor function without .prototype
还有这个:
The difference between putting functions into an object and prototyping them?
但是如果你使用require()
http://docs.nodejitsu.com/articles/getting-started/what-is-require创建新对象,例如:
var Ftp = require("jsftp"),
ftp = new Ftp({
host: "ftp.mywebsite.com",
});
然后假设你稍后执行ftp.getPutSocket()
,它实际上是调用jsftp中的原始Ftp.getPutSocket = function() {}
.js 文件。
现在怎么可能呢?我想如果你执行new Something()
,你只能调用Ftp.prototype.getPutSocket
。那么 require()
在这里发挥了一些魔力吗?
更新1:
所以它与 require()
无关,但基本上是一个 function.call(Ftp.prototype)
行结束。但为什么这给了我错误:
http://jsfiddle.net/qhoc/7j3Vp/
var Test = function() {
console.log('aa');
}
(function() {
this.anotherTest = function() {
console.log('bb');
}
}).call(Test.prototype);
错误:
Uncaught TypeError: Cannot read property 'prototype' of undefined
我尝试做与 https://github.com/sergi/jsftp/blob/master/lib/jsftp.js 相同的事情
最佳答案
定义 getPutSocket
时 ( https://github.com/sergi/jsftp/blob/master/lib/jsftp.js#L620 ),this
实际上是 Ftp.prototype
(请参阅 https://github.com/sergi/jsftp/blob/master/lib/jsftp.js#L803 )。
所以看起来 Ftp.getPutSocket 根本没有被定义。它仅在 Ftp.prototype
上定义。
更新 1:
由于 javascript 评估事物的顺序而失败。首先是函数,然后是变量赋值。
但是,这有效:
function Test() {
console.log('aa');
}
(function() {
this.anotherTest = function() {
console.log('bb');
}
}).call(Test.prototype);
关于javascript - require() 将构造函数转换为原型(prototype)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15131598/