我有一个javascript类,每个方法都返回一个Qpromise.我想知道为什么this未定义method2和method3.有没有更正确的方法来编写此代码?
function MyClass(opts){
this.options = opts;
return this.method1()
.then(this.method2)
.then(this.method3);
}
MyClass.prototype.method1 = function(){
// ...q stuff...
console.log(this.options); // logs "opts" object
return deferred.promise;
};
MyClass.prototype.method2 = function(method1resolve){
// ...q stuff...
console.log(this); // logs undefined
return deferred.promise;
};
MyClass.prototype.method3 = function(method2resolve){
// ...q stuff...
console.log(this); // logs undefined
return deferred.promise;
};
Run Code Online (Sandbox Code Playgroud)
我可以通过使用bind:
function MyClass(opts){
this.options = opts;
return this.method1()
.then(this.method2.bind(this))
.then(this.method3.bind(this));
}
Run Code Online (Sandbox Code Playgroud)
但不完全确定为什么bind有必要; 正在.then()杀戮this?
我正在阅读版本控制npm,显然它提供了一个很好的方便命令来破坏你的软件包版本.
npm version [<newversion> | major | minor | patch | premajor | preminor | prepatch | prerelease]
Run Code Online (Sandbox Code Playgroud)
抢鲜
让我们说你的包从版本开始 0.0.0
npm version prerelease => 0.0.1-0
npm version prerelease => 0.0.1-1
基本上只是破折号之后的数字
的prepatch
从0.0.0使用pre [major | minor | patch]开始代替......
npm version prepatch => 0.0.1-0
npm version preminor => 0.1.0-0
npm version premajor => 1.0.0-0
补丁
从0.0.0使用补丁开始......
npm version patch => 0.0.1
npm version patch => 0.0.2
我理解了碰撞主要版本和补丁版本的规则,但之前版本化事物的标准惯例是1.0.0什么?
在追求100%的代码覆盖率的,我试图用摩卡来测试我的javascript模块下正确加载AMD,CommonJS/Node和browser条件。我使用的模式如下:
我的module.js
(function(global){
function MyClass(){}
// AMD
if(typeof define === 'function' && define.amd){
define(function(){
return MyClass;
});
// CommonJS/Node
} else if (typeof module !== 'undefined' && module.exports){
module.exports = MyClass;
// Browser
} else {
global.MyClass = MyClass;
}
})(this);
Run Code Online (Sandbox Code Playgroud)
由于我使用 node 运行我的测试,define因此从未定义,并且module始终已定义;所以“CommonJS/Node”条件是唯一经过测试的条件。
到目前为止我尝试过的是这样的:
我的module.test.js
var MyClass = require('./my-module');
describe('MyClass', function(){
// suite of tests for the class itself
// uses 'var instance = new MyClass();' in each test …Run Code Online (Sandbox Code Playgroud)