1. 程式人生 > >JS中的delete操作符

JS中的delete操作符

rip 存在 ext destroy math 操作 type oba keyword

首先,delete刪除成功返回true,失敗返回false

js代碼:

function wxCount ($element) {
    this.init($element);
}

wxCount.prototype = {
    init : function(){...}, //初始化方法
    count : function(){...}, //計算方法
    destroy : function(){
        delete this;
    } //刪除方法
}

仔細一看便知,這裏的this指向的是function wxCount(),而在javascript中,delete

是無法刪除一般的變量或者function的,永遠都會返回false

example:

<script type="text/javascript">
    x = 1;         // 創建全局屬性x
    var y = 2;     // var聲明,y為變量
    obj = {
          a : 3,
          b : 4
    };              // 創建全局對象obj,並有a和b兩個成員變量


    delete x;       // returns true

    delete y;       // returns false 

    delete Math.PI; // returns false 

    delete obj.a; // returns true 
    delete obj.b; // returns true 

    delete obj;   // returns true

    function f() {
          var z = 5;
        var obj2 = {
            c : 6,
              d : 7
        }
        obj3 = {
            e : 8
        }
          delete z;     // returns false
        delete obj2;     // returns false
        delete obj2.c;     // returns true
        delete obj3;     // returns true
    }
</script>

大多數情況下可以理解為:通過變量或者函數聲明的屬性不能刪除。

1.全局屬性可以刪除

x = 150;
delete x; //return true

function f() {
    obj = {
        a : 2
    }
}
delete obj; //return true

x可以理解為全局對象GLOBAL的一個屬性,即GLOBAL.x,可以刪除成功。函數中的obj也被置為全局屬性,同理。

2.通過var或者function聲明的屬性不能刪除

var x = 150;
delete x; //return fale
function y() {}
delete y; //return false

3.內置的屬性不能刪除

delete Math.PI //reuturn false
function (param) {
    delete param; //return false
    console.log(param); //1
}(1);

4.原型上的屬性

function People(){}
People.prototype.age = 18;
var Perez = new People();
Perez.age = 100;
console.log(Perez.age); //100
delete Perez.age; //return ture
console.log(Perez.age); //18
//返回成功但是並沒有什麽用,Perez還是會繼承原型上的age屬性

delete People.prototype.age;
console.log(Perez.age); //undefined

5.刪除數組中元素

var ipr = ["zhong","du","sun","an","yuan"];
delete ipr[4];  //return true
console.log(ipr);  //["zhong","du","sun","an"]
console.log(ipr.length);  //5
console.log(4 in ipr);  //false
console.log(ipr[4]);  //undefined

刪除數組中元素,數組長度不會發生變化,但是元素實際不存在數組中了。

var ipr = ["zhong","du","sun","an",undefined];
console.log(4 in ipr);  //ture

如果將最後個元素置為undefined,實際還是存在數組中。

關於delete更深的問題和兼容性問題,可以參考
深入理解JS的delete

JS中的delete操作符