在测试二叉树生成和遍历代码的JS示例时,我用console.log()替换了print()来创建控制台输出。在“case”这个“:func(this.value);”中抛出了“未捕获......非法调用”。为什么这个函数不能像任何其他函数一样作为函数参数传递?从注释代码中可以看出,将“tree”对象传递给console.log只输出函数代码,而不是.value。任何人都可以提供有关此异常情况的指导或更好的记录测试输出的方法吗?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
//20140122-this example code originally had "print" statements in place of console.log, however, console.log cannot be passed as a function parameter.
function BinaryTree(value, left, right) {
this.value = value;
this.left = left;
this.right = right;
}
BinaryTree.prototype.preorder = function(f) { this.walk(f, ['this', 'left', 'right']); };
BinaryTree.prototype.inorder = function(f) { this.walk(f, ['left', 'this', 'right']); };
BinaryTree.prototype.postorder = function(f) { this.walk(f, ['left', 'right', 'this']); };
BinaryTree.prototype.walk = function(func, order) {
for (var i in order)
switch (order[i]) {
case "this":
func(this.value);
break;
case "left":
if (this.left) this.left.walk(func, order);
break;
case "right":
if (this.right) this.right.walk(func, order);
break;
}
};
BinaryTree.prototype.levelorder = function(func) {
var queue = [this];
while (queue.length != 0) {
var node = queue.shift();
func(node.value);
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
};
// convenience function for creating a binary tree
function createBinaryTreeFromArray(ary) {
var left = null, right = null;
if (ary[1]) left = createBinaryTreeFromArray(ary[1]);
if (ary[2]) right = createBinaryTreeFromArray(ary[2]);
return new BinaryTree(ary[0], left, right);
}
var tree = createBinaryTreeFromArray([1, [2, [4, [7]], [5]], [3, [6, [8], [9]]]]);
console.log("*** preorder ***"); tree.preorder(console.log);
console.log("*** inorder ***"); tree.inorder(console.log);
console.log("*** postorder ***"); tree.postorder(console.log);
console.log("*** levelorder ***"); tree.levelorder(console.log);
// console.log("*** preorder ***"); console.log(tree.preorder);
// console.log("*** inorder ***"); console.log(tree.inorder);
// console.log("*** postorder ***"); console.log(tree.postorder);
// console.log("*** levelorder ***"); console.log(tree.levelorder);
// </script>
</head>
<body>
</body>
</html>
答案 0 :(得分:2)
将对象的方法作为参数传递给函数时,会丢失上下文。要保留它,只需将方法绑定到上下文:
tree.levelorder(console.log.bind(console));
例如:
[1,2,3].forEach(console.log)
> TypeError: Illegal invocation
[1,2,3].forEach(console.log.bind(console))
> 1 0 [1, 2, 3]
> 2 1 [1, 2, 3]
> 3 2 [1, 2, 3]