与 javascript 代码中的 "this" 混淆

Confusion with "this" in javascript code

我得到了这个 js 代码和 运行 它,它工作得很好,只是我不完全理解它。 请帮忙!!

<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>

<div class="members-wrapper"></div>


 <script>

  var db = [
     {fname:"oscar", lname:"santosh", email:"oscar@gmail.com", country:"Brazil", id:101},
      {fname:"juan", lname:"mata", email:"mata@gmail.com", country:"Spain", id:102},
   {fname:"eden", lname:"hazard", email:"hazard@gmail.com", country:"Belgium", id:103}
  ];

  function CaseName(str)
    {
    return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
    };

  //our object with channable method

  var cascadeVar ={

    user:"",

    finduser: function(userEmail)
    {
       var arraylen = db.length,i;
       for(i=arraylen-1;i>=0;i--)
       {
         if(db[i].email === userEmail )
         {
          this.user = db[i];
           break;
         }
       }
       return this;
    },

    formatname : function()
    {
    if(this.user){
       this.user.fullname = CaseName(this.user.fname) + " " + CaseName(this.user.lname);
       }
       return this;
    },

    createLayout:function () {
    if (this.user) {
    this.user.viewData = "<h2>Member: " + this.user.fullname + "</h2>" + "<p>ID: " + this.user.id + "</p>" + "<p>Email: " + this.user.email + "</p>";
    }
    return this;
    },

    display : function()
    {

    if (!this.user) return;
    $(".members-wrapper").append(this.user.viewData);
    }   

  };

  cascadeVar.finduser("oscar@gmail.com").formatname().createLayout().display();

 </script>

</body>
</html>

在 finduser 函数中,为什么我必须使用它作为 this.user = db[i];? 是不是因为 user 属于对象 cascadeVar 而 this 指向 cascadeVar。 如果是,为什么没有 "this" 它就不能工作?我知道我很傻,但我仍然很困惑。

如果我忽略 this.?

,函数 finduser() 中的用户是否未定义?

return this 在同一函数中返回什么?

return this 每个函数返回的是什么?

请帮忙!

Javascript中的This指的是当前函数的owner对象(本例为cascadeVar)

没有它,JS 解释器会将 user 理解为作用域为 findUser 函数的动态变量

在每种情况下,this 返回当前函数的所有者,即 cascadeVar。

原作者给了你一个线索,说这个方法是 'channable'(即可链接)。通过在内部返回 cascadeVar 对象,该函数允许递归函数调用。

在 javascript 中,每个函数都有一个上下文。这就是我们所说的 this.
问题是默认情况下,函数的上下文是函数;父对象。所以,是的,您的假设是正确的:user 属于对象 cascadeVar,this 指向 cascadeVar

我经常发现代码可以自己说话,所以让我们举个例子来理解this是如何工作的:

function getName() {
  // what is `this` ?
  return this.userName;
}

var user1 = {
  userName: 'john',
  getName: getName
};

var user2 = {
  userName: 'george'
}

// getName is a global function, meaning that it's parent is window
// in this case, `this` will point to the window object
// and `this.userName` will point to window.userName
// which is undefined
console.log('getName() =>', getName());

// user1.getName is a user1 method, meaning that it's parent is user1
// in this case, `this` will point to user1
// and `this.userName` will point to user1.userName
// which is 'john'
console.log('user1.getName() =>', user1.getName());

// there are other ways that we can dynamically change a function's context
// look into the following function methods: `call`, `apply`, `bind`
console.log('getName.call(user2) =>', getName.call(user2));
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>

关于你的另一个问题,所有的方法return都是this关键字,以保证方法链。这是一种因 jQuery 库而流行的设计模式,它允许您按顺序调用同一对象的多个方法,而无需调用父对象。
这基本上可以让你做一些语法糖,比如调用 a.b().c().d(); 而不是 a.b(); a.c(); a.d();.
而且..当然,这里有一段代码显示了链接的使用:

var calculator = {
  value: 0,
  add: function(n) {
    this.value += n;
    return this;
  },
  substract: function(n) {
    this.value -= n;
    return this;
  },
  multiply: function(n) {
    this.value *= n;
    return this;
  }
};

calculator
  .add(6)
  .substract(2)
  .multiply(2)
  .add(3)
  .substract(5);

console.log('(6 - 2) * 2 + 3 - 5 = ', calculator.value);
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>