1.this指向:
1.定时器的this指向的是window,在严格模式下是undefined
2.函数指向的是祖先对象,也就是调用他的方法,比如:
<script>
var b = function() {
console.log(this);
}
b();
var a = new b();
</script>
第一个指向的是window,而第二个指向的是b
2.new与直接调用的区别
1.当返回的对象是一个非对象的时候,new会直接无视掉他,如果是一个对象,则返回该对象
<script>
var i = 0;
var b = function() {
i++;
return i;
}
console.log(b());
console.log(new b());
</script>
2.当我们new一个函数的时候,在执行函数里的第一条语句之前,首先创建一个空的对象{},并且this等于这个空对象,并 且已经完成了原型链的构建
<script>
var i = 0;
var b = function() {
i++;
console.log(this);
}
b();
new b();
</script>
3.使用原型链添加与直接添加的区别
篇幅问题,不讨论性能,
当我们使用直接添加的时候,是可以去直接用.操作符去获取到的,但是在使用new的时候却是获取不到,原理是因为:
new调用的时候,是会初始化一个对象,然后去复制得到一条原型链。比如
<script>
var parentfunction = function() {
console.log("this is a function called parentfunction");
}
//直接添加
parentfunction.childrenfunction1 = function() {
console.log("this is the children function called children1");
}
//添加到原型链中
parentfunction.prototype.childrenfunction2 = function() {
console.log("this is the children function called children2");
}
parentfunction.childrenfunction1();
parentfunction.childrenfunction2(); //typeerror
var a = new parentfunction();
a.childrenfunction1(); //typeerror
a.childrenfunction2();
</script>
这样的时候,我们可以理解为a就是一个新的函数了
4.iframe的父子相互操作的方法
假设有子iframe页面的id为a,且,该页面含有名字为myalert的方法,既
<iframe src='a.html' id='a'>
</iframe>
function myalert() {
$('body').empty();
}
此时,父级页面操作子界面的方法为:
setTimeout(function() {
document.getElementById("a").contentWindow.myalert('hello,world');
}, 20000);
在相同的情况下,我们在子界面操作父界面的方法为:
parent.alert();