Last active
July 11, 2016 15:45
-
-
Save monochromer/8947097b6ea5ef2040096f1a745bb633 to your computer and use it in GitHub Desktop.
Заимствование методов в JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var slice = Function | |
.prototype | |
.call | |
.bind(Array.prototype.slice); | |
var args = slice(arguments); | |
// Пример | |
// http://davidshariff.com/blog/borrowing-methods-in-javascript/ | |
var scoreCalculator = { | |
getSum: function(results) { | |
var score = 0; | |
for (var i = 0, len = results.length; i < len; i++) { | |
score = score + results[i]; | |
} | |
return score; | |
}, | |
getScore: function() { | |
return scoreCalculator.getSum(this.results) / this.handicap; | |
} | |
}; | |
var player1 = { | |
results: [69, 50, 76], | |
handicap: 8 | |
}; | |
var player2 = { | |
results: [23, 4, 58], | |
handicap: 5 | |
}; | |
var score = Function.prototype.call.bind(scoreCalculator.getScore); | |
// Score: 24.375 | |
console.log('Score: ' + score(player1)); | |
// Score: 17 | |
console.log('Score: ' + score(player2)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment