Каково было бы лучшее название JavaScript “это”?

Вы можете использовать метод _.pull от lodash 2.0 и выше

var fruits = ['Apple', 'Banana', 'Orange', 'Celery'];

_.pull(fruits, 'Apple', 'Banana', 'Orange'); // ['Celery']

document.write(fruits);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.6.1/lodash.js"></script>
10
задан CoderDennis 16 June 2009 в 18:49
поделиться

8 ответов

этот можно разумно переименовать в контекст в Javascript.

Это действительно относится к контексту выполнения для текущей области, и хотя этот контекст может быть экземпляром класса, это, конечно, не обязательно - это может быть любой объект, и он может быть изменен во время выполнения.

Доказательство того, что нет никакой гарантии, что "метод" в Javascript работает с экземпляром "класса", в котором он определен:

function Cat(){

     this.texture = 'fluffy';

     this.greet = function(){
         alert("Pet me, I'm " + this.texture);
     }
 }

 var cat = new Cat();

 // Default to using the cat instance as the this pointer
 cat.greet(); // Alerts "Pet me, I'm fluffy"

 // Manually set the value of the this pointer!
 cat.greet.call({texture: 'scaly'});  // Alerts "Pet me, I'm scaly"

Важно отметить там, что значение объекта this полностью не зависит от того, где определена содержащая функция .

17
ответ дан 3 December 2019 в 14:25
поделиться

Я думаю, что JavaScript this намного ближе к Java this , чем вы думаете. В контексте ООП this означает «этот экземпляр». Я думаю, что может сбивать с толку ключевое слово JavaScript this , так это то, что оно может иметь разное значение в зависимости от контекста.

5
ответ дан 3 December 2019 в 14:25
поделиться

this не является вызывающей функцией функции (хотя может быть) или областью действия, в которой функция была определена (хотя может быть) - это контекст функции .

Изменяющееся значение, на которое ссылается @Andrew Hare, вероятно, ближе к источнику вашего замешательства; из-за механизма наследования прототипов JS ключевое слово function может означать, в зависимости от того, как оно используется, что-то более близкое к классу Java , чем к определению метода Java.

Предполагая выполнение в браузере:

var q = this.document; //this is window

var o = new (function pseudoconstructor(){
    this.property = "something else" //the new keyword changed 'this' to mean 'the object I'm about to return'
})();
3
ответ дан 3 December 2019 в 14:25
поделиться

Как насчет «JavaScript this»? Это будет держать вас в прямой зависимости от того, что вы

1
ответ дан 3 December 2019 в 14:25
поделиться

Я усваиваю новый синтаксис с помощью маленьких простых в использовании ментальных моделей, таких как:

$(document).ready(function() {

  function baffle() {
    alert(this.b);
  }

  function what() {
    this.b = "Hello";
    baffle();
  }

  function huh() {
    this.b = "World";
    baffle();
  }

  what();
  huh();

  }
);

Это плохо переводится на небрежный, воображаемый C ++ как:

template <class This>
function baffle() {
  alert(This.b);
}

function what() {
  b = "Hello";
  baffle<what>();
}

function huh() {
  b = "World";
  baffle<huh>();
}

what();
huh();
0
ответ дан 3 December 2019 в 14:25
поделиться

I think this is most appropriate for historical reasons. There isn't really a one-size-fits-all phrase for this in JavaScript, since not only can it be automatically assigned to very different references, e.g., this in the context of a procedural function or this in the context of an object, but this can also be assigned by the scripter using Function.apply and Function.call.

However, the meaning of this is only adjustable because JavaScript and the DOM work in some very weird ways. For example, the primary use of Function.apply is to preserve the context of an element reference in event calls. You will have seen this in Prototye's Function.bind() method.

this is a placeholder for the context in which the function is being executed, and it's hard to get any more specific than that. However, most uses of this make it a semantically appropriate keyword. In the case of bind(), even though we're using methods to arbitrarily change the meaning of this within the function, it should be used to make this more appropriate than it would be without. Many amateur JavaScript programmers are thrown off by the strange behavior of this in event handlers, and Function.apply is used to right that "wrong".

0
ответ дан 3 December 2019 в 14:25
поделиться

Selfreferential logic (self or this) avoids paradoxes to advantage working on other than the self (this). Shall self (this) keep everything and all to one , it may as well stay static with no instance and with class method (static) instead. To avoid paradoxes, avoid selfreferences and logic keeps all truths provable and viceversa, all provables true.

-1
ответ дан 3 December 2019 в 14:25
поделиться

Одно из возможных альтернативных имен - владелец . Это приведет вас к мысли о том, что владелец может меняться в зависимости от того, какой код вы выполняете.

Этот пример взят из quirksmode :

В JavaScript это всегда относится к «владельцу» функции, которую мы выполняем, или, скорее, к объекту, методом которого функция является. Когда мы определяем нашу точную функцию doSomething () на странице, ее владельцем является страница или, скорее, объект окна (или глобальный объект) JavaScript. Однако свойство onclick принадлежит элементу HTML, которому оно принадлежит.

В следующем коде

function doSomething() {
   this.style.color = '#cc0000';
}

и

element.onclick = doSomething;

, владелец указывает на объект, содержащий метод, когда он выполнен.

------------ window --------------------------------------
|                                          / \           |
|                                           |            |
|                                          this          |
|   ----------------                        |            |
|   | HTML element | <-- this         -----------------  |
|   ----------------      |           | doSomething() |  |
|               |         |           -----------------  |
|          --------------------                          |
|          | onclick property |                          |
|          --------------------                          |
|                                                        |
----------------------------------------------------------
9
ответ дан 3 December 2019 в 14:25
поделиться