我正在Binary Search Tree
用Java语言实现一个简单的方法,但是我无法理解Javascript OOP的工作方式。
在我的insertHelper
方法中,我分配了一个新的root用户,BinaryNode
但是在函数返回后,它null
甚至仍然明确地this
在insert
方法中使用了指针。那么有人可以帮我解释一下吗?
function BinaryNode(key, value, left, right) {
this.key = key;
this.value = value;
this.left = left;
this.right = right;
}
function BinarySearchTree() {
this.root = null;
}
BinarySearchTree.prototype.insertHelper = function (root, key, value) {
if (root === null) {
root = new BinaryNode(key, value, null, null);
}
}
BinarySearchTree.prototype.insert = function (key, value) {
this.insertHelper(this.root, key, value);
if (this.root === null) {
console.log("root is NULL!");
}
};
var bst = new BinarySearchTree();
console.log(typeof bst);
console.log(typeof bst.root);
bst.insert(1, 1);
封闭,this.root
存在undefined
是您必须显式处理的一种特殊情况。我会让您弄清楚如何立即完成实施insertHelper
。
操作方式的问题是,您正在重新分配范围变量,而您需要在this
对象上重新分配该变量。
BinarySearchTree.prototype.insert = function (key, value) {
if (this.root == null) {
this.root = new BinaryNode(key, value);
} else {
this.insertHelper(this.root, key, value);
}
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句