1、普通函數中this的指向( 普通函數中的this指針指向于調用者)
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指向與構造函數創建的對象:this的調用者是new
// setInterval(this.show, 2000);
// 由new來給定時器綁定一個函數
// setInterval(function(){
// // this指向于window;因為this是由定時器調起執行的
// 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對象調用,所以方法中的this指針指向了window對象
window.obj();
4、在構造函數中的this的指向
function CreatePerson() {
this.name = '小璇';
// 如果在構造函數中向外返回一個對象,則該對象會覆蓋由new創建出來的對象
// return {
// name: '小李子'
// }
// 構造函數不能向外返回引用類型,因為返回的引用類型會替換掉new創建出來的對象
// 如果向外返回的是null對象,則不會替換
return null;
}
// 因為new調用函數執行時:1、開辟一塊內存空間;2、把函數中this的指向指為這塊空間;3、把創建出來的空間交給變量
var per = new CreatePerson();
console.log(per.name);
5、在事件函數中的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、事件函數中嵌套函數的this指向
利用call修復bug:在事件函數中,this指向元素,但是在內部再包含一個函數后,在函數內再繼續調用this的話,那么現在的this指針就指向了window了
window.onload = function () {
var btn = document.querySelector('#btn');
btn.onclick = function () {
console.log(this);--btn
// 如果事件函數中嵌套了函數,該函數又出現了this指針,則該指針指向window對象
// hello()
//解決辦法:
// hello.call(this);--btn
function hello() {
console.log(this);--window
}
}
}
<button type="button" id='btn' name="button">點我</button>
7、內存相關概念
1字節=8位
console.log(0.999999999999999999-0.1);
內存分區:常量區、靜態區、堆區、棧區、代碼區
常量區:存放定義的常量
靜態區:存放的是靜態變量
棧區: 由系統開辟并維護的空間,大部分的變量都在該區域存放
堆區:由程序員開辟并維護的空間,手動開辟空間保存的內容存放在堆區
代碼區:存放代碼的區域
垃圾回收機制(GC):js仿照java語言實現的內存管理方式,每隔若干時間,垃圾回收機制啟動, 把所有不再使用的變量、數據所占用的內存空間銷毀掉。
棧區管理內存的方式是使用“棧”這種數據結構管理的
堆區管理內存是使用垃圾回收機制管理的