当我阅读john的教程时,有很多'assert' &log函数,我知道它们能做什么,但我不知道如何定义这两个函数。我试过了,但是失败了。
function assert(){return console.log;}
log
和assert
很可能与console.log
和console.assert
是一样的。但是,如果您希望log
和assert
可以调用这些函数,请尝试以下操作:
function log(info){
console.log(info);
}
function assert(info){
console.assert(info);
}
然后你可以在必要的时候使用这些函数:
> log('Hello World')
Hello World
> log('foo bar')
foo bar
> assert(5==6)
Assertion failed:
> assert(5==5)
assert
引用了他的书《Secrets of the Javascript Ninja -
var output = document.getElementById('output');
function assert( outcome, description ) {
var li = document.createElement('li');
li.className = outcome ? 'pass' : 'fail';
li.appendChild( document.createTextNode( description ) );
output.appendChild(li);
};
,如下所述。我认为log
只是console.log的包装函数,确保它支持该浏览器,像这样-
function log(msg) {
if (console && console.log) {
console.log(msg);
}
}
要从头开始实现assert
,您可以这样做:
function AssertionError(message) {
this.name = "AssertionError";
this.message = (message || "");
}
AssertionError.prototype = Error.prototype;
function assert(proposition, complaint) {
if (!proposition) throw new AssertionError(complaint);
}
如果不回到console.log
,就不能真正定义log
。除非你"打印"到文档中。