了解Javascript中的上下文

时间:2018-01-09 11:06:56

标签: javascript

我很难理解上下文在JavaScript中的工作方式,或者特别是这个的价值。在我的情况下,我有Person构造函数,返回一个对象。根据我的理解,这个值取决于调用函数的方式。例如,像这样调用person函数" Person()" 。返回的值将是窗口。然后我如何确保传递的人员值正是返回的



function Person(personName,Title,Phone,Email,Id, picUrl, description){
     var myusername = this.username;
    var myTitle = this.Title;
    var myPhone = this.Phone;
    var myEmail = this.Email;
    var myId = this.Id;
    var mypicUrl = this.picUrl;
    var mydescription = this.description;

    return {
        name: myusername,
        Title: myTitle,
        phoneNumber: myPhone,
        Email: myEmail,
        UserId: myId,
        PictureUrl: mypicUrl,
        Description: mydescription
    }

}

function getallDetails (){

var PeopleCompleteList = [];
for (i=0; i< data.d.results.length; i++) {                           
    if(data.d.results[i]['Name'] != null){
      personName = data.d.results[i]['Name'].Name.split('|')[2];
      userName = data.d.results[i]['Name']['Name'];
      UserTitle = data.d.results[i]['Name']['Title'];
      UserphoneNumber = data.d.results[i]['Name']['WorkPhone'];
      UserEmail = data.d.results[i]['Name']['EMail'];
      Id = data.d.results[i]['Name']['Id'];
      picUrl= WebURL + '/_layouts/15/userphoto.aspx?size=L&accountname='+UserEmail;
      description = data.d.results[i]['pozb'];
      PeopleCompleteList.push(Person(personName, UserTitle, UserphoneNumber,UserEmail,Id, picUrl, description));
    
      }
         
    }
   }//end function
                                
                                
 
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:0)

正如@CBroe和@Icepickle在评论中所说,你没有使用Person函数作为构造函数。您需要使用new关键字调用您的方法。通过这样做:

  • 您函数中的this关键字将是您愿意创建的对象的引用(否则它将是对全局对象的引用)
  • 函数不需要返回任何内容,因为它隐式返回this引用的对象

我建议你阅读这篇文章:MDN - the new operator

同时,下面的代码段显示了如果使用Person函数作为构造函数,代码会是什么样子

&#13;
&#13;
function Person(personName, title, phone, email, id, picUrl, description) {
   // populating the object behind the 'this' reference with each argument
   // if you call this method with the 'new' keyword, 'this' will be a reference to the instance you are creating
   
   this.username = personName;
   this.title = title;
   this.phoneNumber = phone;
   this.email = email;
   this.userId = Id;
   this.pictureUrl = picUrl;
   this.description = description;

   // if this function is called with the 'new' keyword, you don't have to return anything. the reference behind 'this' will be implicitly returned 
}

function getallDetails() {
  // local variable declarations are usually put on top of the function 
  var peopleCompleteList = [], personName, userName, userTitle, userphoneNumber, userEmail, id, picUrl, description;
  for (i=0; i< data.d.results.length; i++) {                           
    if (data.d.results[i]['Name'] != null) {
      personName = data.d.results[i]['Name'].Name.split('|')[2];
      userName = data.d.results[i]['Name']['Name'];
      userTitle = data.d.results[i]['Name']['Title'];
      userphoneNumber = data.d.results[i]['Name']['WorkPhone'];
      userEmail = data.d.results[i]['Name']['EMail'];
      id = data.d.results[i]['Name']['Id'];
      picUrl= WebURL + '/_layouts/15/userphoto.aspx?size=L&accountname='+UserEmail;
      description = data.d.results[i]['pozb'];
      // adding the 'new' keyword before invoking the Person method 
      peopleCompleteList.push(new Person(personName, userTitle, userphoneNumber,userEmail,Id, picUrl, description));
      }
   }
}//end function
&#13;
&#13;
&#13;

情侣旁注:

  • var函数中声明变量时,您忘记使用getallDetails关键字。这是一个不好的做法,因为它们都是全局变量,并且在执行getallDetails函数后不会被清除
  • 您的大多数变量声明都违反了JavaScript variable naming convention。我使用适当的变量名更新了代码段(使用camelCase表示法)。

答案 1 :(得分:0)

简单来说,您可以说上下文是所在的位置。例如:

    <script> 
     function show() {
       this.context = 'sudhir';
     }
    </script>

这相当于

    <script>
     var context;
     function show() {
       this.context = 'sudhir';
     }
   </script>

这两个函数都写在全局范围内。所以,这个指的是全局意味着范围或您的上下文是全局的。现在让我们看看有趣的例子:

    <script>
      function newContext() {
        var a = function show() {
          this.context = 'sudhir';
        }
      }
    </script>

这相当于写在这里:

   <script>     
     function newContext() {
       var context;
       var a = function show() {
          this.context = 'sudhir';
       }
     }
     </script>

这里这个指的是写在newContext函数范围内的函数show。因此, this 的上下文是newContext。

答案 2 :(得分:0)

我会告诉你我将要做的事情。 首先,如果您创建了一个对象,则不必返回值。

function Person(personName,Title,Phone,Email,Id, picUrl, description){
    this.personName = personName;
    [...]
    this.mydescription = description;
}

然后你实例化你的&#34;类&#34;喜欢:

var person = new Person('David', ..., 'some description');

并且访问属性:

console.log('Person name is', person.personName);

JavaScript&#34;这&#34;关于功能范围,例如:

    function Person(personName,Title,Phone,Email,Id, picUrl, description){
        this.personName = personName;
        [...]
        this.mydescription = description;

        function someAnonymousFunction(){
           console.log('Person name is', this.personName); // Person name is Undefined
// Because this is a reference to someAnonymousFunction
        }
    }

保存这个的Javascript技巧是在变量中存储上下文:

function Person(personName,Title,Phone,Email,Id, picUrl, description){    
    var self = this;
    this.personName = personName;
    [...]
    this.mydescription = description;

    function someAnonymousFunction(){
         console.log('Person name is', self.personName); // Person name is David
         // Because we use self variable instead of this here
    }
}

但你有一个更简单的方法
ECMAScript 2015包含类语法。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

如果您关心导航器兼容性,则必须使用TypeScript
https://www.typescriptlang.org/ Typescript允许您编写更易读的JavaScript代码,尤其是关于类的代码。然后,你可以&#34;编译&#34;通过在输出文件中选择所需的JavaScript版本,在JavaScript中使用您的代码。

希望它有所帮助,

迈克尔