今天总结了几道,感觉非常有意思的题,有感兴趣的可以看下,有疑问请留言~
(答案在最后)
1.
考察自执行函数的this指向
审题要细心
var n = 2,
obj = {
n:2,
fn:(function(n){
n*=2;
this.n+=2;
console.log(this.n);
console.log(window.n);
return function(m){
this.n*=2;
console.log(m+(++n))
}
}(n)
};
var fn = obj.fn;
fn(3);
obj.fn(3)
console.log(n,obj.n);
- prototype:原型属性
_proto_: 原型链属性
hasOwnProperty:检测属性是否属于当前对象私有属性
function Fn() {
var n = 100;
this.AA = function () { }
this.BB = function () { }
}
Fn.prototype.AA = function () { }
var f1 = new Fn();
var f2 = new Fn;
console.log(f1.n);
console.log(f1.AA === f2.AA);
console.log(f1.__proto__.AA === f2.AA)
console.log(f1.__proto__.AA === f2.__proto__.AA)
console.log(f1.__proto_.AA === Fn.prototype.AA)
console.log(f1.hasOwnProperty('AA') === Fn.prototype.hasOwnProperty('AA'));
- 比较简单的一道题
console.log(a); a = 20; function fn(){ console.log(a) var a = 12; } fn(); console.log(a)
- 考察变量提升
var foo = 1; function fn(){ if(!foo){ var foo = 12; } console.log(foo); } fn();
- 函数形参变量和arguments存在映射
函数默认返回undefinedvar a = 4; function test(x,y,a){ console.log(a); arguments[2] = 100; console.log(a) } a = test(1,2,3); console.log(a)
- 函数形参变量和arguments映射建立在函数执行形参赋值的一刻
形参和实参一一对应,多出来的不建立映射function fn(x,y){ var arg = arguments; arg[0] = 100; var y = 200; arg[1] = 300; console.log(y); } fn(20);
- 逻辑与 逻辑或
console.log(0||1&&2||0||3&&2||1)
- 还是考察this
var num = 10;
var obj = {num:20};
obj.fn = (function(num){
num = this.num + 10;
this.num = num + 10;
return function(){
this.num += ++num;
}
})(num)
var fn = obj.fn;
fn();
obj.fn();
console.log(num,obj.num)
- 很长的一段
10)还是this得问题(发现了好多this的题)function Fn(){ this.x = 100; this.y = 200; this.getX = function(){ console.log(this.x) } } Fn.prototype.getX = function(){ console.log(this.x) } Fn.prototype.getY = function(){ console.log(this.y) } var f1 = new Fn; var f2 = new Fn; console.log(f1.getX === f2.getX); console.log(f1.getY === f2.getY); console.log(f1.__proto__getY === Fn.prototype.getY); console.log(f1.__proto__.getX === f2.getX); console.log(f1.getX === Fn.prototype.getX); console.log(f1.constructor); console.log(Fn.prototype.__proto__.constructor); f1.getX(); f1.__proto__.getX(); f2.getY(); Fn.prototype.getY();
var name = 'window'; var Tom = { name:'Tom', show:function(){ console.log(this.name) }, wait:function(){ var fun = this.show; fun(); } } Tom.wait();
答案:
- 9
10
8 6 - undefined
false
false
true
true
true - a is not defined
- 12
- 3
100
undefined - 200
- 2(逻辑与的优先级高于逻辑或)
- 51 42
- false
true
true
false
false
Fn
Object
100
undefined;this:f1.proto ,上面没有x,所以是undefined
200
undefined;this:Fn.prototype,上面没有y,所以是undefined - window