相关疑难解决方法(0)

在JavaScript原型函数中保留对"this"的引用

我刚刚开始使用原型JavaScript,并且我很难弄清楚this当范围发生变化时如何在原型函数内保留对主对象的引用.让我说明一下我的意思(我在这里使用jQuery):

MyClass = function() {
  this.element = $('#element');
  this.myValue = 'something';

  // some more code
}

MyClass.prototype.myfunc = function() {
  // at this point, "this" refers to the instance of MyClass

  this.element.click(function() {
    // at this point, "this" refers to the DOM element
    // but what if I want to access the original "this.myValue"?
  });
}

new MyClass();
Run Code Online (Sandbox Code Playgroud)

我知道我可以通过以下方式执行此操作来保留对主对象的引用myfunc:

var myThis = this;
Run Code Online (Sandbox Code Playgroud)

然后使用myThis.myValue访问主对象的属性.但是当我有一大堆原型函数时会发生什么MyClass?我是否必须this在每个开头保存引用?似乎应该有一个更清洁的方式.这样的情况怎么样:

MyClass = function() {
  this.elements $('.elements'); …
Run Code Online (Sandbox Code Playgroud)

javascript oop scope this prototype-programming

89
推荐指数
3
解决办法
6万
查看次数

标签 统计

javascript ×1

oop ×1

prototype-programming ×1

scope ×1

this ×1