首頁  >  文章  >  web前端  >  JS物件導向的詳細介紹(二)

JS物件導向的詳細介紹(二)

零下一度
零下一度原創
2017-06-29 13:37:501029瀏覽

選單導航,《JS物件導向筆記一》,  參考書籍:阮一峰之《JavaScript標準參考教學》

一、建構子與new指令

二、this關鍵字

三、建構子與new指令



  1. 五、建構子與new指令

    六、建構子與new指令
  2. 2、建構函數與new指令

  3. 八、建構子與new指令


一、建構子與new指令

1、建構子
JavaScript語言的物件體系,不是基於「類別」的,而是基於建構子(constructor)和原型鏈(prototype)

為了與普通函數區別,建構函數名字的第一個字母通常大寫,例如:  var Person = function(){  this.name = '王大錘';  }

建構函數的特性: 

       a、函數體內部使用了

this
關鍵字,代表了所要產生的物件實例;   b、產生物件的時候,必需用new
指令呼叫此建構函數
2、new 

  作用:就是執行建構函數,傳回一個實例物件

var Person = function(name, age){this.name = name;this.age = age;this.email = 'cnblogs@sina.com';this.eat = function(){
        console.log(this.name + ' is eating noodles');
    }
}var per = new Person('王大锤', 18);
console.log(per.name + ', ' + per.age + ', ' + per.email); //王大锤, 18, cnblogs@sina.comper.eat();  //王大锤 is eating noodles
執行new指令時的原理步驟:
#建立一個空對象,作為將要傳回的物件實例
## ####將這個空物件的原型,指向建構函數的###prototype###屬性#############將這個空物件賦值給函數內部的###this## #關鍵字############開始執行建構函式內部的程式碼#############注意點:當建構函式裡面有return關鍵字時,如果傳回的是非對象,new指令會忽略傳回的訊息,最後返回時建構之後的this物件;###  如果return回傳的是與this無關的新對象,則最後new指令會傳回新對象,而不是this物件。範例程式碼:###############
console.log('---- 返回字符串 start ----');var Person = function(){this.name = '王大锤';return '罗小虎';
}var per = new Person();for (var item in per){
    console.log( item + ': ' + per[item] );
}//---- 返回字符串 start ----//name: 王大锤console.log('----- 返回对象 start ----');var PersonTwo = function(){this.name = '倚天剑';return {nickname: '屠龙刀', price: 9999 };
}var per2 = new PersonTwo();for (var item in per2){
    console.log(item + ': ' + per2[item]);
}//----- 返回对象 start ----//nickname: 屠龙刀//price: 9999
######View Code######### #####如果呼叫建構函數的時候,忘記使用new關鍵字,則建構函數裡面的this為全域對象window,屬性也會變成全域屬性,######則被建構子賦值的變數不再是一個對象,而是一個未定義的變數,js不允許為undefined新增屬性,所以呼叫undefined的屬性會報錯。 ######範例:###############
var Person = function(){ 
    console.log( this == window );  //truethis.price = 5188; 
}var per = Person();
console.log(price); //5188console.log(per);  //undefinedconsole.log('......_-_'); //......_-_console.log(per.price); //Uncaught TypeError: Cannot read property 'helloPrice' of undefined
#######View Code#########為了規避忘記new關鍵字現象,有一種解決方式,就是在函數內部第一行加上: 'use strict';######表示函數使用嚴格模式,函數內部的this不能指向全域物件window, 預設為undefined, 導致不加new調用會報錯誤###############
var Person = function(){ 'use strict';
    console.log( this );  //undefinedthis.price = 5188; //Uncaught TypeError: Cannot set property 'helloPrice' of undefined}var per = Person();
######View Code######

另外一种解决方式,就是在函数内部手动添加new命令:

var Person = function(){ //先判断this是否为Person的实例对象,不是就new一个if (!(this instanceof Person)){return new Person();
    }
    console.log( this );  //Person {}this.price = 5188; 
}var per = Person(); 
console.log(per.price); //5188
View Code

 

 

二、this关键字

var Person = function(){
    console.log('1111'); 
    console.log(this); this.name = '王大锤';this.age = 18;this.run = function(){
        console.log('this is Person的实例对象吗:' + (this instanceof Person) ); 
        console.log(this); 
    }
}var per = new Person();
per.run();/* 打印日志:
1111
Person {}
this is Person的实例对象吗:true
Person {name: "王大锤", age: 18, run: function}*/console.log('---------------');var Employ = {
    email: 'cnblogs@sina.com',
    name: '赵日天',
    eat: function(){
        console.log(this);
    }
}

console.log(Employ.email + ', ' + Employ.name);
Employ.eat();/* 打印日志:
---------------
cnblogs@sina.com, 赵日天
Object {email: "cnblogs@sina.com", name: "赵日天", eat: function}*/
View Code

1、this总是返回一个对象,返回属性或方法当前所在的对象, 如上示例代码

2、对象的属性可以赋值给另一个对象,即属性所在的当前对象可变化,this的指向可变化

var A = { 
    name: '王大锤', 
    getInfo: function(){return '姓名:' + this.name;
    } 
}var B = { name: '赵日天' };

B.getInfo = A.getInfo;
console.log( B.getInfo() ); //姓名:赵日天//A.getInfo属性赋给B, 于是B.getInfo就表示getInfo方法所在的当前对象是B, 所以这时的this.name就指向B.name
View Code

 3、由于this指向的可变化性,在层级比较多的函数中需要注意使用this。一般来说,在多层函数中需要使用this时,设置一个变量来固定this的值,然后在内层函数中这个变量。

示例1:多层中的this

//1、多层中的this (错误演示)var o = {
    f1: function(){
        console.log(this); //这个this指的是o对象var f2 = function(){
            console.log(this);
        }();//由于写法是(function(){ })() 格式, 则f2中的this指的是顶层对象window    }
}

o.f1();/* 打印日志:
Object {f1: function}

Window {stop: function, open: function, alert: function, confirm: function, prompt: function…}*///2、上面代码的另一种写法(相同效果)var temp = function(){
    console.log(this);
}var o = {
    f1: function(){
        console.log(this); //这个this指o对象var f2 = temp(); //temp()中的this指向顶层对象window    }
}
o.f1(); 
/* 打印日志
Object {f1: function}

Window {stop: function, open: function, alert: function, confirm: function, prompt: function…}*///表示上面两种写法是一样的效果,this的错误演示//3、多层中this的正确使用:使用一个变量来固定this对象,然后在内层中调用该变量var o = {
    f1: function(){
        console.log(this); //o对象var that = this;var f2 = function(){
            console.log(that); //这个that指向o对象        }();
    }
}
o.f1();/* 打印日志:
Object {f1: function}
Object {f1: function}*/
View Code

示例2: 数组遍历中的this

//1、多层中数组遍历中this的使用 (错误演示)var obj = {
    email: '大锤@sina.com', 
    arr: ['aaa', 'bbb', '333'],
    fun: function(){//第一个this指的是obj对象this.arr.forEach(function(item){//这个this指的是顶层对象window, 由于window没有email变量,则为undefinedconsole.log(this.email + ': ' + item);
        });
    }
}

obj.fun(); 
/* 打印结果:
undefined: aaa
undefined: bbb
undefined: 333 *///2、多层中数组遍历中this的使用 (正确演示,第一种写法)var obj = {
    email: '大锤@sina.com', 
    arr: ['aaa', 'bbb', '333'],
    fun: function(){//第一个this指的是obj对象var that = this; //将this用变量固定下来this.arr.forEach(function(item){//这个that指的是对象objconsole.log(that.email + ': ' + item);
        });
    }
}
obj.fun(); //调用/* 打印日志:
大锤@sina.com: aaa
大锤@sina.com: bbb
大锤@sina.com: 333 *///3、多层中数组遍历中this正确使用第二种写法:将this作为forEach方法的第二个参数,固定循环中的运行环境var obj = {
    email: '大锤@sina.com', 
    arr: ['aaa', 'bbb', '333'],
    fun: function(){//第一个this指的是obj对象this.arr.forEach(function(item){//这个this从来自参数this, 指向obj对象console.log(this.email + ': ' + item);
        }, this);
    }
}
obj.fun(); //调用/* 打印日志:
大锤@sina.com: aaa
大锤@sina.com: bbb
大锤@sina.com: 333 */
View Code

 

4、关于js提供的call、apply、bind方法对this的固定和切换的用法

  1)、function.prototype.call(): 函数实例的call方法,可以指定函数内部this的指向(即函数执行时所在的作用域),然后在所指定的作用域中,调用该函数。
  如果call(args)里面的参数不传,或者为null、undefined、window, 则默认传入全局顶级对象window;
  如果call里面的参数传入自定义对象obj, 则函数内部的this指向自定义对象obj, 在obj作用域中运行该函数

var obj = {};var f = function(){
    console.log(this);return this;
}

console.log('....start.....');
f();
f.call();
f.call(null);
f.call(undefined);
f.call(window);
console.log('**** call方法的参数如果为空、null和undefined, 则默认传入全局等级window;如果call方法传入自定义对象obj,则函数f会在对象obj的作用域中运行 ****');
f.call(obj);
console.log('.....end.....');/* 打印日志:
....start.....
Window {stop: function, open: function, alert: function, confirm: function, prompt: function…}
Window {stop: function, open: function, alert: function, confirm: function, prompt: function…}
Window {stop: function, open: function, alert: function, confirm: function, prompt: function…}
Window {stop: function, open: function, alert: function, confirm: function, prompt: function…}
Window {stop: function, open: function, alert: function, confirm: function, prompt: function…}
**** call方法的参数如果为空、null和undefined, 则默认传入全局等级window;如果call方法传入自定义对象obj,则函数f会在对象obj的作用域中运行 ****
Object {}
.....end.....*/
View Code

 

以上是JS物件導向的詳細介紹(二)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn