Javascript: A background of inference from "duck type"
Learning Dynamic language all know a word: "If it walks like a duck, and it is called a duck, then it is Duck", JavaScript also supports duck type, the following is about duck type in JavaScript two scenarios.
Two inferences
- Any such signature method: Object.Method (Arg1, arg2, ...) method, can be used method.apply (object, [Arg1, Arg2, ...]) Conduct research.
- Some methods of array (do not modify the array state) can use arguments with Array.prototype.method.apply (ARGUMENTS,[ARG1, arg2, ...]) Called by the method.
- The former: treat array as arguments (duck)
- The latter: treat argument as an array (duck)
A small test
The idiomatic approach in JavaScript
1 Console.log (Math.max.apply (Math, [3,2,1]));23var arr = [1,2, 3] 4 Array.prototype.push.apply (arr, [4, 5, 6 Console.log (arr); 6 Span style= "color: #008080;" > 7 8 var Arr = Array.prototype.slice.apply (arguments); 9 Console.log (arr); 10}) (1, 3);
We'll imitate the ducks ourselves.
1 3 }); 2 Console.log (arr);
Note
Duck type and implicit interface are a little bit similar, it expands the concept of polymorphism.
Original: http://www.cnblogs.com/happyframework/p/3239790.html
JavaScript Duck Model