首页 > 初学javascript,将一个变量赋给另一个变量,是否是赋值了一个拷贝?

初学javascript,将一个变量赋给另一个变量,是否是赋值了一个拷贝?

我的本意是想知道当一个实例node是另一个实例root的成员时,用node来调用root的cut()方法是什么效果?也就是一个变量调用了另一个变量的方法来销毁自己,感觉有点像循环引用?
结果我这段代码却出现了另一个问题

test.html

<!DOCTYPE html>
<html>
<head>
    <title>test</title>
</head>
<style>
    #root{
        background: #000;
    }
    #node{
        background: yellow;
    }
    #node2{
        background: blue;
    }
</style>
<body>
<div id="root">
    <div id="node">node</div>
    <div id="node2">node2</div>
</div>
<script type="text/javascript" src="test.js"></script>
</body>
</html>

test.js

function Node(ele) {
    this.ele = ele;
    this.children = [];
    this.cut = function () {
        for (var i = 0; i<this.children.length; i++){
            this.children[i] = null;
        }
    };
    this.parent = null;
}

var root = new Node(document.getElementById("root"));
var node = new Node(document.getElementById("node"));
var node2 = new Node(document.getElementById("node2"));
node.parent = root;
node2.parent = root;

window.onload = function () {
    root.children.push(node);
    root.children.push(node2);
    node.parent.cut();
};

发现node.parent.cut();并不能使node变成null,这是否是弱引用?
没想明白,还请高手赐教。


你这里都是拿到dom对象,把对象变成空?在js里面null本身也是个 object。 如果你要具体地操作dom对象增减什么 用appendChild() removeChild()或者innerHtml = ""


并不是什么弱引用,而是js在参数传递的时候是按照值传递的,你修改了地址的copy的引用对象并不能对原对象修改。


怎么说呢,JavaScript 参数是按值传递的,这个坑我以前也踩过,可以看下我写的文章 http://www.cnblogs.com/zichi/...

【热门文章】
【热门文章】