Javascript 笔记与总结(1-4)this
js 中函數(shù)的 4 種調(diào)用方式:
① 作為普通函數(shù)來調(diào)用,this 的值指向 window,準(zhǔn)確地說,this 為 null,被解釋成為 window。在 ECMAScript5 標(biāo)準(zhǔn)中,如果 this 為 null,則解釋成 undefined
<script> function t(){this.x = 'hello'; } t(); alert(window.x); </script>彈出:hello
?
② a.作為對(duì)象的方法來調(diào)用,this 指向方法的調(diào)用者,即該對(duì)象
<script> var obj = {x:'hello',y:'world',t:function(){alert(this.x)}}; obj.t(); </script>彈出:hello
?
b.
<script> var obj = {x:'hello',y:'world',t:function(){alert(this.x)}};var dog = {x:'wang'}; dog.t = obj.t; dog.t(); </script>彈出:wang
作為方法調(diào)用時(shí),this 指向其調(diào)用那一刻的調(diào)用者,即母體對(duì)象,不管被調(diào)用函數(shù),聲明時(shí)屬于方法還是函數(shù)
?
c.
<script> var obj = {x:'hello',y:'world',t:function(){alert(this.x)}};var dog = {x:'wang'}; dog.t = obj.t; dog.t();show = function(){alert('show '+this.x); } dog.t = show; dog.t(); </script>?
d.
<script> var obj = {x:'hello',y:'world',t:function(){alert(this.x)}};var dog = {x:'wang'}; dog.t = obj.t; dog.t();show = function(){alert('show '+this.x); } dog.t = show; dog.t(); </script>彈出:show wang
?
③ 作為構(gòu)造函數(shù)調(diào)用時(shí)
js 中沒有類的概念,創(chuàng)建對(duì)象使用構(gòu)造函數(shù)來完成,或者直接用 json 格式{} 來寫對(duì)象
<script> function Dog(name,age){this.name = name;this.age = age;this.bark = function(){alert(this.name);} } var dog = new Dog('妞妞',2); dog.bark(); </script>彈出:妞妞
new Dog 發(fā)生了一下幾個(gè)步驟:
a. 系統(tǒng)創(chuàng)建空對(duì)象{},(空對(duì)象 construct 屬性指向 Dog 函數(shù))
b. 把函數(shù)的 this 指向該空對(duì)象
c. 執(zhí)行該函數(shù)
d. 返回該對(duì)象
?
例:
<script> function Robit(){this.name = '瓦力';return 'wali'; } var robit = new Robit(); console.log(robit); </script>這段代碼將輸出?
答案:
Robit {name: "瓦力"}輸出的是 Robit 對(duì)象,因?yàn)?strong>函數(shù)作為構(gòu)造函數(shù)運(yùn)行時(shí),return 的值是忽略的,依然返回對(duì)象(return 無意義)。
?
?
④ 函數(shù)通過 call,apply 調(diào)用
語法格式:函數(shù).call(對(duì)象,參數(shù)1,參數(shù)2...參數(shù)n);
<script> function t(num){alert('我的年齡是 '+this.age);alert('雖然我看起來像 '+(this.age+num)); } var human = {name:'迭戈.科斯塔',age:27}; human.t = t; human.t(10); </script>彈出:我的年齡是 27
彈出:雖然我看起來像 28
?
接下來,不把 t 賦為 human 的屬性,也能把 this 指向 human
<script> function t(num){alert('我的年齡是 '+this.age);alert('雖然我看起來像 '+(this.age+num)); }var giroud = {name:'Giroud',age:28}; t.call(giroud,-5); </script>彈出:我的年齡是 28
彈出:雖然我看起來像 23
【分析】:
fn.call(對(duì)象,參數(shù)1,參數(shù)2...參數(shù)n);
運(yùn)行如下:
a. fn 函數(shù)中的 this 指向?qū)ο?obj
b. 運(yùn)行 fn(參數(shù)1,參數(shù)2...參數(shù)n)
?
轉(zhuǎn)載于:https://www.cnblogs.com/dee0912/p/4430658.html
總結(jié)
以上是生活随笔為你收集整理的Javascript 笔记与总结(1-4)this的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 跨域上传图片的尝试过程,最终成功了---
- 下一篇: Java算法-符号~