Skip to content

Instantly share code, notes, and snippets.

@DimitryRd
Last active May 28, 2020 21:48
Show Gist options
  • Save DimitryRd/9a047061106743cc94f213d49fd11016 to your computer and use it in GitHub Desktop.
Save DimitryRd/9a047061106743cc94f213d49fd11016 to your computer and use it in GitHub Desktop.
Function invocation and this
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8>" />
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<div id="div" style="cursor: pointer;">
<p>person.name</p>
</div>
<script>
// https://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/
//Base object
const person = {
name: 'Dimitry Rudakov',
hello: function () {
console.log(this.name + ' says hello world');
},
};
$('#div').click(person.hello.bind(person));
// Bind + apply
// const bind = function (func, thisValue) {
// return function () {
// return func.apply(thisValue, arguments);
// };
// };
// var boundHello = bind(person.hello, person);
// boundHello('Inna');
// // Call using object method
// var boundHello = function (thing) {
// return person.hello.call(person, thing);
// };
// boundHello('Inna');
// //Strict mode
// ('strict mode');
// let object = {
// property1: 12312,
// prop2: '3452345',
// func: function () {
// return this.property;
// },
// };
// function hello(thing) {
// console.log('Hello ' + thing);
// }
// hello('world');
// hello.call(window, 'world>>>');
// // Broken example
// let deck = {
// suits: ['hearts', 'spades', 'clubs', 'diamonds'],
// cards: Array(52),
// createCardPicker: function () {
// return function () {
// let pickedCard = Math.floor(Math.random() * 52);
// let pickedSuit = Math.floor(pickedCard / 13);
// return {
// suit: this.suits[pickedSuit] /* <<< Unaccessible this */,
// card: pickedCard % 13,
// };
// };
// },
// };
// let cardPicker = deck.createCardPicker();
// let pickedCard = cardPicker();
// alert('card: ' + pickedCard.card + ' of ' + pickedCard.suit);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment