1、普通函數(shù)中this的指向( 普通函數(shù)中的this指針指向于調(diào)用者)
function fn (){
this.name = 'wang';
console.log(this);--window
console.log(this.name);--wang
}
window.fn();
console.log(name);--wang
var name = '小王';
var obj = {
name : 'wang',
fn : function () {
console.log(this);--Object(name:wang,fn:obj.fn())
console.log(this.name);--wang
}
}
obj.fn();
2靡挥、定時器中的this的指向
function CreatePerson () {
this.name = '小璇';
// this指向與構造函數(shù)創(chuàng)建的對象:this的調(diào)用者是new
// setInterval(this.show, 2000);
// 由new來給定時器綁定一個函數(shù)
// setInterval(function(){
// // this指向于window坟奥;因為this是由定時器調(diào)起執(zhí)行的
// console.log(this);
// }, 2000);
//
//把this的指向固定在self變量中
var self = this;
setInterval(function(){
// 此時,self指向的是對象
self.show();
}, 2000);
}
CreatePerson.prototype.show = function (){
// console.log('hello');
console.log(this);
}
var per =new CreatePerson();
3婴栽、在對象方法中的this指向
var name = '小李子';
var per = {
name: '小璇',
fn: function () {
console.log(this.name);
}
}
var obj = per.fn;
// fn方法交給了window對象調(diào)用满粗,所以方法中的this指針指向了window對象
window.obj();
4、在構造函數(shù)中的this的指向
function CreatePerson() {
this.name = '小璇';
// 如果在構造函數(shù)中向外返回一個對象愚争,則該對象會覆蓋由new創(chuàng)建出來的對象
// return {
// name: '小李子'
// }
// 構造函數(shù)不能向外返回引用類型映皆,因為返回的引用類型會替換掉new創(chuàng)建出來的對象
// 如果向外返回的是null對象,則不會替換
return null;
}
// 因為new調(diào)用函數(shù)執(zhí)行時:1轰枝、開辟一塊內(nèi)存空間捅彻;2、把函數(shù)中this的指向指為這塊空間;3鞍陨、把創(chuàng)建出來的空間交給變量
var per = new CreatePerson();
console.log(per.name);
5步淹、在事件函數(shù)中的this的指向
function Btn() {
this.b = 23;
var _this = this;--object Btn對象
document.getElementById('btn').onclick = function (){
// this.show();--btn元素
_this.show();--Btn對象
};
//document.getElementById('btn').onclick = this.show;若不改變指針的指向則this指向的是這個div,而不是new出來的對象
}
Btn.prototype.show = function() {
console.log(this.b);--Object(b:23);23
};
window.onload = function () {
new Btn();
}
<div style='width:100px;height:100px;border:1px solid black' id="btn">
6、事件函數(shù)中嵌套函數(shù)的this指向
利用call修復bug:在事件函數(shù)中缭裆,this指向元素键闺,但是在內(nèi)部再包含一個函數(shù)后,在函數(shù)內(nèi)再繼續(xù)調(diào)用this的話澈驼,那么現(xiàn)在的this指針就指向了window了
window.onload = function () {
var btn = document.querySelector('#btn');
btn.onclick = function () {
console.log(this);--btn
// 如果事件函數(shù)中嵌套了函數(shù)辛燥,該函數(shù)又出現(xiàn)了this指針,則該指針指向window對象
// hello()
//解決辦法:
// hello.call(this);--btn
function hello() {
console.log(this);--window
}
}
}
<button type="button" id='btn' name="button">點我</button>
7缝其、內(nèi)存相關概念
1字節(jié)=8位
console.log(0.999999999999999999-0.1);
內(nèi)存分區(qū):常量區(qū)挎塌、靜態(tài)區(qū)、堆區(qū)氏淑、棧區(qū)勃蜘、代碼區(qū)
常量區(qū):存放定義的常量
靜態(tài)區(qū):存放的是靜態(tài)變量
棧區(qū): 由系統(tǒng)開辟并維護的空間,大部分的變量都在該區(qū)域存放
堆區(qū):由程序員開辟并維護的空間假残,手動開辟空間保存的內(nèi)容存放在堆區(qū)
代碼區(qū):存放代碼的區(qū)域
垃圾回收機制(GC):js仿照java語言實現(xiàn)的內(nèi)存管理方式缭贡,每隔若干時間,垃圾回收機制啟動辉懒, 把所有不再使用的變量阳惹、數(shù)據(jù)所占用的內(nèi)存空間銷毀掉。
棧區(qū)管理內(nèi)存的方式是使用“椏袅”這種數(shù)據(jù)結構管理的
堆區(qū)管理內(nèi)存是使用垃圾回收機制管理的