如何在 John Resig 的高级 JavaScript 教程中定义'assert'



当我阅读john的教程时,有很多'assert' &log函数,我知道它们能做什么,但我不知道如何定义这两个函数。我试过了,但是失败了。

    function assert(){return console.log;}

logassert很可能与console.logconsole.assert是一样的。但是,如果您希望logassert可以调用这些函数,请尝试以下操作:

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。除非你"打印"到文档中。

相关内容

最新更新