//分析:String的两种建立方法: //第一种方法: var str = "str" //str只是一个以String为数据类型的值,但并不属于String对象的实例 //第二种方法: var strObj = new String("strObj") //此时的strObj是String对象的一个实例 //针对第一种建立方式,采用typeof检测,此时采用instanceof != String //针对第二种建立方式,采用instanceof检测,此时采用typeof检测出来的是Object function isString(str){ return (typeof str).toLowerCase() === 'string' || str instanceof String }
function Foo(){ getName = function(){ alert(1)} } Foo.getName = function(){alert(2)} Foo.prototype.getName = function(alert(3)) var getName = function(){alert(4)} function getName(){alert(5)} //问题:请给出下面运行的结果 Foo.getname(); getName(); Foo().getName(); getName(); New Foo.getName(); new Foo().getName(); new new Foo().getName();
进入环境(代码未执行,已编译):javascript
VO:{ Foo:{ <reference to function> getName:<reference to function(){alert(1)}> return this } getName:<reference to function(){alert(5}> }
代码执行1:Foo.getName()
前端
VO:{ Foo:{ <reference to function>, getName:<reference to function(){alert(2)}>, return this }, getName:<reference to function(){alert(5)}> }
代码执行2:Foo.prototype.getName = function(){alert(3)}
java
VO:{ Foo:{ <reference to function> getName:<reference to function(){alert(2)}>, prototype:{ getName:<reference to function(){alert(3)}> } return this } getName:<reference to function(){alert(5)}> }
代码执行3:var getName = function(){alert(4);};
面试
VO:{ Foo:{ <reference to function> getName:<reference to function(){alert(2)}>, prototype:{ getName:<reference to function(){alert(3)}> } return this } getName:<reference to function(){alert(4)}> }
代码执行4:Foo.getName()
函数
VO:{ Foo:{ <reference to function> getName:<reference to function(){alert(2)}>, prototype:{ getName:<reference to function(){alert(3)}> } return this } getName:<reference to function(){alert(4)}> }
代码执行5:getName() //2
代码执行6:Foo().getName()
this
Foo().getName() == window.getName() //同时注意:这里因为Foo()调用,致使VO发生了变化。最后alert(1) VO:{ Foo:{ <reference to function> getName:<reference to function(){alert(2)}>, prototype:{ getName:<reference to function(){alert(3)}> } return this } getName:<reference to function(){alert(1)}> }
代码执行7:getName() //1
代码执行8,9,10:prototype
//调用优先顺序 成员访问 > new(带参数列表)>函数调用>new(无参数列表)
var name = 'the window' var obje = { name:'myObject', getNameFunc:function(){ return function(){ return this.name } } } obje.getNameFunc()()
var stringValue = 'lorem ipsum dolor sit amet ,consectent adipisicing elit' var array = [] var pos = stringValue.indexOf('e') while(pos > -1){ array.push(pos) pos = stringValue.indexOf('e',++pos) }
var a =1; function foo(a,b){ a = 2; console.log(a); var a; console.log(a); arguments[0] = 3 console.log(a,this.a,b) }
//2 //2 //2 1 undefined