发布于 1970-01-01 08:00
  • 3 个回答
    • 函数定义如下;

      function showmsg()
      {
        console.log(this);
      }
      

      首先函数大致有三种调用方式

      1 直接调用的话 默认this是全局对象Window

      showmsg();
      
      //Window {top: Window, window: Window, location: Location, external: Object, chrome: Object…}
      

      2 如果把一个函数绑定到某个对象上去 那么this就是那个对象了

      var obj = {a: 1, b: 2, showmsg: showmsg};
      obj.showmsg();
      
      //Object {a: 1, b: 2, showmsg: function}
      

      3 还有一种方式作为构造器使用
      根据第二条的结论 User当中的this就是showmsg当中的this
      那么User当中的this是什么呢?

      function User(name, age)
      {
        this.name = name;
        this.age = age;
        this.showmsg = showmsg;
      }
      
      var u = new User("wiz", 21);
      u.showmsg();
      
      //User {name: "wiz", age: 21, showmsg: function}
      

      由此看来this还是个对象 只不过constructor变成了User
      构造器当中的this实际上是new了一个Object 然后把constructor变成了这个函数

      =============================

      看你问题改了 补充一下吧

      obj.a(); //静态调用
      
      var a = "...";
      obj[a](); //动态调用
      
      (function(...){...})(this);
      

      定义一个函数对象后马上调用它 这样不需要给函数一个名字
      括号的作用是把语句转化为表达式

      2022-11-24 05:49 回答
    • this的指向大致有四种:

      1.函数调用的时候,this指向window

      function aa(){
          console.log(this)
      }
      aa()    //window
      

      2.当是方法调用的时候,this指向方法所在的对象

      var a={}
      a.name = 'hello';
      a.getName = function(){
          console.log(this.name)
      }
      a.getName()    //'hello'
      

      3.构造函数模式的时候,this指向新生成的实例

      function Aaa(name){
          this.name= name;
          this.getName=function(){
              console.log(this.name)
          }
      }
      var a = new Aaa('kitty');
      a.getName()    //  'kitty'
      var b = new Aaa('bobo');
      b.getName()    //  'bobo'
      

      4,apply/call的时候,this指向`apply/call方法中的第一个参数。

      var list1 = {name:'andy'}
      var list2 = {name:'peter'}
      
      function d(){
          console.log(this.name)
      }
      d.call(list1)  //  'andy' 
      d.call(list2)  //  'peter' 
      
      2022-11-24 05:49 回答
    • 题主,你是不理解which this val么?
      如果是,我这里描述一下。


      this指向的是function的调用对象 //大概这么理解

      所以 里面那个this,就表示User {};

      (function(w){
        //调用w
        w;
      })(a);//实际上w就相当于a了
      

      对应你这个例子,效果就是使得 你后面 user.getname是一个function

      而那个val,例子没点出来用法,就是user.setname("我是技术宅")
      想想function函数表达式和定义表达式。

      2022-11-24 05:49 回答
    撰写答案
    今天,你开发时遇到什么问题呢?
    立即提问
    PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
    Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有