最常使用的方法,物件的方法調用時,須注意在哪個物件下呼叫
var fullarea = 'fullarea';
function callFullArea(fullarea) {
var area = fullarea;
var full = this.fullarea
console.log(area, full); //area fullarea
}
callFullArea('area');
函式調用(window調用),this指向window物件,因此this.fullarea會是全域變數的fullarea
要看this指向何處,可直接印出來看看
(function callFunc() {
console.log(this);
})();
var func = function callFunc() {
console.log(this);
}
var newfunc = func;
var userInfo = {
firstName: 'Chen',
lastName: 'Jay',
fullName: function(){
console.log(this.firstName + ' ' + this.lastName);
}
}
userInfo.fullName();//Jay Chen
//this指向userInfo
function UserInfo(lastName, firstName){
this.firstName = firstName;
this.lastName = lastName;
}
var jayInfo = new UserInfo('Jay','Chen');
console.log(jayInfo);
var janeInfo = new UserInfo('Jane','Wang');
console.log(jayInfo);
call()、apply()是改變 this 指向的物件,直接執行一個 function
bind()是綁定 this 指向的物件,用來建立一個新的 function
fun.call(obj, val1, val2);
function.apply(obj, [val1, val2]);
fun.bind(obj, val1, val2)(); fun.bind(obj)(val1, val2);
var company = {
department: 'depart-a'
};
function Employee (name, age) {
console.log(this, name, age);
}
Employee.call(company, 'Jay', 32);
Employee.call(undefind, 'Jay', 32);
//呼叫fun時提供this值。參數不傳或者傳 null 、undefined,默認 this 指向全局對象(非嚴格模式)或 undefined(嚴格模式)
Employee.apply(company, ['Amy', 24]);
var Employee2 = Employee.bind(company, 'Jason', 22);
Employee2();
使用"use strict"可以撰寫出較嚴謹的js,可防止一些不合理、不嚴謹之處,像是設定變數未定義,提高編譯器效率,增加執行速度。
"use strict";
function userInfo() {
name = 'Joe'; //報錯 name未定義
}
userInfo();