几个有意思的题目,进来看看
发布于 8 年前 作者 zouzhenxing 4317 次浏览 来自 分享
var a = 1; a.b = 2; a + a.b = ?
var a = "abc";a.b = "123";a + a.b = ?

var fn  = function(){
        console.log(a);
		var a = 1;
		console.log(a);
}();
(function(){
        console.log(a);
		(function(){
		     var a = 1;
			 console.log(a);
		})();
})();
\n```
13 回复

有没有高手分析下原理啊

这样写代码的一巴掌拍死

这样写代码的一巴掌拍死

这样写代码的一巴掌拍死

别拍了,就是我看到的面试题而已。呵呵 From Noder

说说自己的想法,有错误希望改正。 第一二两行的代码,应该设计到包装函数,对于Number,String等基本类型的数据,当给他们赋予属性的时候,会自己调用他们对于的包装函数,并赋予属性,但是当这句赋值属性的代码结束之后,属性会自动清除(我记得在JavaScript高级程序中有这种情况的描述),所以后面的a.b的值为undefined,所以a + a.b = NaN;

之后的两个应该涉及到变量声明提前,JavaScript在解析程序的时候,会检索整个作用域里面的代码,先把函数声明提前,再把变量声明提前。

首先,这样写代码的一巴掌拍死,出这种题的一般是扯蛋

其次:

  1. number string 是属于immutable,也就是不可变类型,所以你赋值给a.b是没用的,a.b取的值一直是undefined,具体类似a = ‘12345’; a[0] = ‘6’; 结果a还是’12345’。(特别说下,a = 4; a = 5; 结果的5和原来的4是没关系的,是new了一个5的number赋值给a)
  2. 后面两个,js里面function是一个单独的作用域,var的声明会被提前,可以理解为你在函数里面写了个var a = 2; 执行的时候一进函数,会自动执行一个var a; 然后才执行你写的代码,注意,这里是var a; 所以第3个问题console.log出来是undefined。第四个问题,在console.log当前作用域里面没有var a = xxx; console.log出来肯定是报错,变量未定义

前面2个问题,普通模式下楼上的答案就可以了,但是有一点,在strict模式下,对于包装对象的赋值操作是不允许的,会抛出中断error;后面两个问题比较简单了,前者是var的变量提升,后面就是纯粹函数作用域的问题了

第一题得3 第二题abc123 自豪地采用 CNodeJS ionic

@bendise 醉了。。。。。。你这都错了

@eyblog 要的就是这效果,出题的人就是要看乐子的 自豪地采用 CNodeJS ionic

面试题吧,就是让你不会,然后好压价。 From Noder

关于 var a = 1; a.b = 2; http://ecma-international.org/ecma-262/5.1/#sec-8.7.2
8.7.2 PutValue (V, W)

… 4.Else if IsPropertyReference(V), then
a. If HasPrimitiveBase(V) is false, then let put be the [[Put]] internal method of base, otherwise let put be the special [[Put]] internal method defined below.
b. Call the put internal method using base as its this value, and passing GetReferencedName(V) for the property name, W for the value, and IsStrictReference(V) for the Throw flag. …

由于 var a = 1;, 所以 HasPrimitiveBase(V)true, 将使用下面这个put内部方法,

The following [[Put]] internal method is used by PutValue when V is a property reference with a primitive base value. It is called using base as its this value and with property P, value W, and Boolean flag Throw as arguments. The following steps are taken: … 7.Else, this is a request to create an own property on the transient object O
a. If Throw is true, then throw a TypeError exception.
8.Return.

b不是a的属性, 去到了7, 如果是严格模式, 将抛出一个 TypeError, 否则Return

回到顶部