JavaScript

prototype, random

Naranjito 2021. 1. 12. 19:27

Prototype : It provides ingeritance, objects can have a prototype object, which acts as a template object that it inherits methods and properties from.

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <title>Document</title>
</head>
<body>
    <script>
        /*
        var arr=new Array('a','b','c','d','e');
        function getRandomFromArray(arr){
            var index=Math.floor(arr.length*Math.random());
            //get random integer as long as length of arr
            //Math.floor returns the largest or equal integer that is less than given value
        
            return arr[index];
        }
        console.log(getRandomFromArray(arr));
        */

        Array.prototype.random=function(){ //random method added to Array object
            //random is obviously belong to Array
            var index=Math.floor(this.length*Math.random());//this indicates Arary
            return this[index];
        }
        var arr=new Array('a','b','c','d','e');
        console.log(arr.random());
        
    </script> 
</body>
</html> 

'JavaScript' 카테고리의 다른 글

constructor, this  (0) 2021.01.12
object, encapsulation, information hiding, interface  (0) 2021.01.11
arguments, function  (0) 2021.01.11
ajax, closure  (0) 2021.01.11
global variable, anonymous function  (0) 2021.01.07