在javascript对象方法中使用'this'

时间:2016-09-24 23:04:41

标签: javascript this

我理解函数上下文是javascript中的可塑性概念。但是,为什么在从对象中的另一个成员方法调用成员方法时必须先添加this

var o = {
     m1: function() {

     },
     m2: function() {
         this.m1(); // works
         m1(); // does not work
     }
};

为什么{/ 1}}不能被j / s收集?

2 个答案:

答案 0 :(得分:0)

  

为什么不能通过j / s收集上下文?

这不是关于罐头和罐头的问题。 Javascript引擎设计以使用某些概念,例如scopeexecution context。仅用几行就很难对这些概念进行全面解释。但这里有(非常)宽泛的界限。

范围

Javascript使用词法范围。

这是一个概念,用于定义任何给定function可以访问的变量。这取决于您编写代码的方式。根据这个概念,任何给定的函数都可以访问您放置的变量:

  • 在全球范围内;
  • 在包含相关功能的任何功能中。

这可以通过以下示例来说明:

var one = 'one' //in the global scope

function A () { // access to one and two
    var two = 'two'

    function B () { // access to one, two and three
        var three = 'three'}

        function C () { // access to one, two, three and four
            var four = 'four'
        };
    };
};

如果您在functionvalue property object,则method成为var one = 'one' var myObj = { // in the global scope myFunctions: { myFunction1: function() {}, // have access to one and myObj myFunction2: function() {} // have access to one and myObj } }; 。方法只能访问全局范围(忽略嵌套在方法中的函数)和自身内部的变量:

m1

这就是为什么您的示例必须通过调用o.m1()来访问this;

执行上下文

函数始终具有this值(忽略箭头函数)。

this的值始终是对象中的属性。确定哪个对象取决于函数的执行上下文。执行上下文更具体地取决于函数的 callsite ,因为var one = 'one' var myObj = { two: 'two', three: 'three', myFunction: function () { // this points to myFunction, two and three function () { //this points to one and myObj } }; 的值将设置为:

  • 包含函数调用的对象(级别);或者如果没有包含在另一个函数中
  • 全局对象

这可以通过一个例子来说明:

this

现在上面的例子实际上是什么才能真正让你认为现在你明白了this,因此你降低了你的警卫,在你知道它之前var myObj = { name: 'myObj', myFunction: function() {console.log(this.name) }; var anotherObj = { name: 'anotherObj', notAnotherFunction: myObj.myFunction }; myObj.Myfunction(); // myObj anotherObj.notAnotherFunction(); // anotherObj 正在咬你的** 。记住有关该功能 呼叫网站 的部分 非常重要

this

在上面的示例中,相同的函数被调用两次但调用了不同的调用点,因此具有不同的echo值。

我建议你阅读You don't know JS系列文章,如果你想自学,可以了解上述概念。

答案 1 :(得分:-2)

好的,this指的是Object本身相对于其使用的上下文。 o是您的对象,m1m2是您对象的成员(方法)。
在调用m1()而不是this.m1()时,javascript会在同一范围内寻找一个函数(不是对象,而是在它之外)。
它只是一个简短的解释,你可以在这里找到更多:
MDN - this