zoukankan      html  css  js  c++  java
  • javascript中this的妙用

    this是javascript语言的一个关键字,它代表函数运行时,自动生成的一个内部对象,只能在函数内部使用。
    
    this总是指向对象,并且为调用函数的那个对象;
    
    //调用普通函数
    function fn() {
        document.write(this);                 //[object Window]
        document.write(this.constructor);     //[object Window]
    }
    var o = fn(); //window.fn()
    
    //调用对象函数
    function fn() {
        document.write(this);                 //[object Object]  
        document.write(this.constructor);     //function fn(){code}  
    }
    var o = new fn(); 	
    
    分解var o = new fn();
    
    1.先创建新的对象,并把这个对象赋给变量o:var o = {};
    2.然后再调用函数fn():fn.call(o);  
    
    完整结构如下:
    function fn() {
        document.write(this);                 //[object Object]  
        document.write(this.constructor);     //function Object() { [native code] } 
    }
    var o = {};
    fn.call(o); //调用fn方法的是o对象,所以当前的对象(this)为([object Object])
    
    
    一般对象的声明方式:
    var o = window.o || {};
    o.fn = function(p){
        document.write(this);                 //[object Object]  当前对象为o
    }
    
  • 相关阅读:
    gan研究思路
    官方文档的学习
    构建Pytorch虚拟环境
    桌面显示【我的电脑】
    【VUE】计数器模块
    【品优购】字体图标定位的做法
    029垃圾分代回收机制
    03特殊for语句
    28包 package
    jdk特性
  • 原文地址:https://www.cnblogs.com/sntetwt/p/3298932.html
Copyright © 2011-2022 走看看