Skip to content

Instantly share code, notes, and snippets.

@bloodyowl
Created February 11, 2014 14:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bloodyowl/8935967 to your computer and use it in GitHub Desktop.
Save bloodyowl/8935967 to your computer and use it in GitHub Desktop.
rappels sur la thisValue

rappels sur la thisValue

sans MemberExpression

En mode strict :

(function(){
  "use strict"
  return this
})() 
// undefined

Sinon :

(function(){
  return this
})()
// [object Global]

avec MemberExpression

var object = {
  getThis : function(){
    return this
  }
}
object.getThis() 
// object

si l'on ôte le MemberExpression, on se retrouve dans le même cas que précédemment :

var getThis = object.getThis
getThis()
// [object Global]

prototypes

La thisValue dans une méthode appartenant au [[Prototype]] d'un object est la même que si la méthode était directement possédée par l'object.

function O(){}
O.prototype.getThis = function(){
  return this
}
var o = new O()
o.getThis === O.prototype.getThis
// true
o.getThis() 
// o
// -> o est MemberExpression dans cet appel

définir la thisValue

Les méthodes Function.prototype.call et Function.prototype.apply permettent d'appeler la function avec une thisValue définie (leur premier argument).

function getScopeExample(param){
  return [this, param]
}
getScopeExample(1)
// [[object Global], 1]
getScopeExample.call("foo", 1)
// [Object("foo"), 1]

Si la fonction n'est pas en mode strict, la string "foo" est convertie par ToObject.

function getScopeExample(param){
  "use strict"
  return [this, param]
}

getScopeExample.call("foo", 1)
// ["foo", 1]

bloquer la thisValue

Function.prototype.bind retourne une nouvelle function qui appelera la function concernée avec une certaine thisValue et optionnellement des arguments préremplis.

function foo(a,b){
  "use strict"
  return [this, a, b]
}
var bar = foo.bind(0, 1)
// function(){ [native code] }
bar()
// [0, 1, undefined]
bar(2)
// [0, 1, 2]
bar.call("foo", 2)
// [0, 1, 2]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment