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
    }
    
  • 相关阅读:
    程序员那些事
    Android studio导入eclipse工程时出现中文全部乱码问题
    环境搭建贴
    Android涉及到的网址都记录在这把~~~~
    好书记录
    网络资源整理
    C# 资源
    samba 服务器
    我的虚拟机上网记录
    共享资源链接
  • 原文地址:https://www.cnblogs.com/sntetwt/p/3298932.html
Copyright © 2011-2022 走看看