Skip to content

Instantly share code, notes, and snippets.

@jikeytang
Created August 13, 2014 13:21
Show Gist options
  • Save jikeytang/4a506320202dec2fe9c1 to your computer and use it in GitHub Desktop.
Save jikeytang/4a506320202dec2fe9c1 to your computer and use it in GitHub Desktop.
[ Javascript ] - 20140814-题目1
(function(x){
delete x; return x;
})(1);
求出以上表达式的值,为什么?
PS:
1. 回复时注意加上下面这句话,才会有语法高亮或格式缩进。
```javascript
// you code
```
2. 粘贴代码时请使用shift+tab,缩进前面的空白。
@jikeytang
Copy link
Author

delete删除对象实例的属性,只对对象实例操作,不会影响到他的类型和原型

eval比较特殊,参考
http://tech.idv2.com/2008/01/09/javascript-variables-and-delete-operator/#content_2_4

通过var声明的变量和通过function声明的函数拥有DontDelete特性,
无法被删除。如果你曾经用闭包模拟过类的私有属性、方法,那也可以这样理解,通过var和
function声明的变量和有名函数,都是可以看做类的私有的成员,私有成员具有DontDelete特性。

其它:

:当被delete的对象的属性存在并且拥有
DontDelete时返回false,否则返回true。这里的一个特点就是,对象属性不存在时也返回
true,所以返回值并非完全等同于删除成功与否。

参考:

http://www.cnblogs.com/kaima/archive/2009/03/19/1417040.html
http://blog.charlee.li/javascript-variables-and-delete-operator/
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/delete

@rambo-panda
Copy link

window.x=100;
(function(x){
    delete window.x; return x;
})(1);   // 初学的时候 被这个整过

@wsgouwan
Copy link

(function(x){
        //  相当于  var x = 1 ;
        //  delete x ; 因为声明的变量不会被删除,这个在非严格模式中无效
        //  return x ; 值仍然为1
    })(1);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment