• 原生js之 “this ”(来源于书本:你不知道的javaScript)


    1:先看一个误解的this使用.

     1 function foo(num) {
     2 console.log('foo'+num);
     3 this.data++;        //记录foo()被调用的次数.
     4     console.log(this.data);  //这个data不是外面那个data
     5    i++;
     6    console.log('全局变量i'+i);
     7 //在这里使用了词法作用域.并没有解释this,foo为函数对象.
     8    console.log('foo.data'+foo.data++);
     9 }
    10 foo.data = 0;  //data是函数对象的变量
    11 var i = 0;    //这是一个全局变量
    12 while (i<=5)
    13 {
    14     foo(i);
    15     i++;
    16 }
    17 console.log(foo.data);
    18 console.log(this.data);

    2:在对象中使用this。

     1 function prints()
     2 {
     3     for(ps in this)
     4     {
     5         if('function'===typeof this[ps])
     6             continue  //跳过方法
     7     document.write('<br>&nbsp;&nbsp;属性'+p+'='+this[ps])//输出属性及其值
     8     }
     9 }
    10 function Book(name,price)
    11 {
    12     this.name = name   //使用this访问当前对象
    13     this.price = price
    14     this.insert = prints
    15 }
    16 var s = new Book('c++入门',40)  //执行构造函数
    17 document.write('<br>')
    18 document.write('对象s:')
    19 document.write('<br>')
    20 s.insert() //执行对象方法;

    3:this全面讲解:this的绑定取决于函数的调用位置

      (1)调用位置:即函数被调用的位置:

     1 function test() {
     2 console.log('test'); //当前调用栈是全局作用域
     3     test1();
     4 }
     5 function test1() {
     6 test2();
     7 }
     8 function test2() {
     9 console.log('test2');
    10 }
    11 test(); //test的调用位置.

      (2):绑定规则:this是在运行时进行绑定的,并不是在编写时绑定,它的上下文取决于函数调用时的各种条件。this的绑定和函数声明的位置没有任何关系,只取决于函数的调用方式.

    当一个函数被调用时,会创建一个活动记录(有时候也称为执行上下文)。这个记录会包含函数在哪里被调用(调用栈)、函数的调用方式、传入的参数等信息。this就是这个记录的一个属性,会在函数执行的过程中用到。

      原文:的意思是非严格模式下this绑定全局对象,this.a被解析成全局变量a = 2。

     1 1:默认绑定
     2 //代码三:默认绑定:
     3 /*非严格模式下
     4 function test() {
     5 console.log(this.a);
     6 }
     7 var a = 2;
     8 test();   //输出的是undefined
     9  */
    10 /*严格模式下
    11 function test() {
    12 'use strict';
    13     console.log(this.a);
    14 }
    15 var a = 2;
    16 test();  //直接报错.
    17  */

      隐式绑定

     1 //隐式绑定.
     2 /*
     3 function test(num) {
     4 console.log(this.s); //此时的this绑定于对象a。
     5 console.log(num);
     6 }
     7 var a = {
     8     s:0,
     9     a_test:test  //该处是用对象的属性来引用函数.
    10 };
    11 a.a_test(4);  //输出0 ,4.
    12  */
    13 function foo() {
    14 console.log(this.a);  //this绑定的是对象obj2
    15 }
    16 var  obj2 = {
    17     a:42,
    18     obj2_foo:foo  //对象obj2的属性obj2_foo来引用函数foo()
    19 };
    20 var obj1 = {
    21     a:2,
    22     obj1_obj2:obj2   //对象obj1的属性obj1_obj2来引用对象obj2
    23 };
    24 obj1.obj1_obj2.obj2_foo();  //42
  • 相关阅读:
    struts1下载地址
    基础知识浮点数
    基础知识this[String]
    矩阵基础知识(二)
    矩阵基础知识(三)
    設計公司軟件開發需求分析流程
    動態調用js文件
    图片的淡入淡出的实现方法
    IIS7.5(经典/集成),IIS6,asp.net 4.0下配置Url映射(asp.net mvc)
    页面状态加载....
  • 原文地址:https://www.cnblogs.com/1314bjwg/p/12260595.html
Copyright © 2020-2023  润新知