js构造函数

这是js权威指南上的一个例子,我运行的时候报了 Illegal invocation 错误。。我是我不知道为什这样写会报错,求告知。谢谢。代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <script>
        function Range(from, to) {
            this.from = from;
            this.to = to;
        }
        Range.prototype = {
        includes: function(x) { return this.from <= x && x <= this.to; },
        foreach: function(f) {
            for(var x = Math.ceil(this.from); x <= this.to; x++){
                f(x);
            } 
        },
        toString: function() { return "(" + this.from + "..." + this.to + ")"; }
    };
    var r = new Range(1,3);   // Create a range object
    r.includes(2);            // => true: 2 is in the range
    r.foreach(console.log);   // Prints 1 2 3
    console.log(r);           // Prints (1...3)
    </script>
</body>
</html>
阅读 3.4k
3 个回答
r.foreach(console.log); 
//改成
r.foreach(console.log.bind(console)); 

原因在于 console.log 这个函数实现需要 console 作为函数的 this

这样改一下就可以了:

function Range(from, to) {
    this.from = from;
    this.to = to;
}
Range.prototype = {
    includes: function(x) { return this.from <= x && x <= this.to; },
    foreach: function(f) {
        for(var x = Math.ceil(this.from); x <= this.to; x++){
            f(x);
        } 
    },
    toString: function() { return "(" + this.from + "..." + this.to + ")"; },
    log : function(x){
        console.log(x);
    }
};
var r = new Range(1,3);   // Create a range object
r.includes(2);            // => true: 2 is in the range
r.foreach(r.log);   // Prints 1 2 3
console.log(r);           // Prints (1...3)

具体原因可参考:http://bbs.csdn.net/topics/390619932

因为 log /info 等使用时,上下文需要是 console

console.info("stuff")
stuff
console.info.call(this, "stuff")
TypeError: Illegal invocation
console.info.call(console, "stuff")
stuff
function Range(from, to) {
            this.from = from;
            this.to = to;
        }
        Range.prototype = {
        includes: function(x) { return this.from <= x && x <= this.to; },
        foreach: function(f) {
            for(var x = Math.ceil(this.from); x <= this.to; x++){
                f(x);
            } 
        },
        toString: function() { return "(" + this.from + "..." + this.to + ")"; }
    };
    var r = new Range(1,3);   // Create a range object
    r.includes(2);            // => true: 2 is in the range
    r.foreach(console.log.bind(console));   // Prints 1 2 3
    
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题