What is the purpose of the delete operator in Javascript?

后端 未结 6 981
一向
一向 2020-12-04 14:22

The behaviour of the delete operator seems very complicated and there are many misunderstandings about what it actually does. To me, it seems that reassigning something to <

6条回答
  •  伪装坚强ぢ
    2020-12-04 14:55

    Does delete have any purpose that cannot be acheived by reassignment to undefined?

    Yes. If you want to unmask a property from a prototype or cause in, hasOwnProperty, and for (...in...) to not record the property as existing then delete is appropriate.

    let set = {};
    
    set._x = true;
    
    alert('_x' in set);  // true
    
    set._x = undefined;
    
    alert('_x' in set);  // true
    
    delete set._x;
    
    alert('_x' in set);  // false
    

    EDIT: As T.J. Crowder explains:

    The purpose of the delete operator is to completely remove a property from an object, whereas setting a property to undefined just sets the property to undefined.

    This matters in its own right, but it also matters when you're using inheritance, because if O derives from P

    let P = { prop: 42 };
    let O = Object.create(P);  // P is O's prototype.
    

    when you retrieve O.prop, you get the value of prop from O if O has a property with that name (even if its value is undefined), but if O doesn't have the property at all, then the value will be retrieved from P.prop instead.

    console.log(O.prop);  // "42" since O doesn't have its own prop, but P does.
    O.prop = undefined;
    console.log(O.prop);  // "undefined" since O has its own prop.
    delete O.prop;
    console.log(O.prop);  // "42" since the delete "unmasked" P.prop.
    

提交回复
热议问题