iwato Posted May 25, 2018 Share Posted May 25, 2018 (edited) PROBLEM: The following script is purported to add a select number of zeros to the left of a numerical value. Although it appears logically correct, I do not know how to call the function thus created. The SCRIPT Number.prototype.pad = function(size) { var s = String(this); while (s.length < (size || 2)) {s = "0" + s;} return s; } REQUEST: Could someone please give an example of how I could convert the number 2 to appear as 002 using the above script. Roddy Edited May 25, 2018 by iwato Link to comment Share on other sites More sharing options...
dsonesuk Posted May 25, 2018 Share Posted May 25, 2018 <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" id="viewport" content="target-densitydpi=high-dpi,initial-scale=1.0"> <title>Document Title</title> </head> <body> <div id="demo"></div> <script> Number.prototype.pad = function(size) { var s = String(this); while (s.length < (size || 2)) { s = "0" + s; } return s; } var demoDiv = document.getElementById("demo"); demoDiv.innerHTML += "<p>" + (2).pad(3) + "</p>"; // => "002" demoDiv.innerHTML += "<p>" + (10).pad(3) + "</p>" // => "010" demoDiv.innerHTML += "<p>" + (100).pad(3) + "</p>" // => "100" </script> </body> </html> 1 Link to comment Share on other sites More sharing options...
iwato Posted May 25, 2018 Author Share Posted May 25, 2018 Great! But ... I still do not understand it. What pray-tell is the meaning of the numbers enclosed in parentheses. Do the parentheses convert the number number into an object? Roddy Link to comment Share on other sites More sharing options...
dsonesuk Posted May 25, 2018 Share Posted May 25, 2018 (edited) Its Explained here https://www.w3schools.com/jsref/jsref_prototype_num.asp It deals with creating a new number method, the example you give takes the (2) and uses as number to be converted in the method which is called by the '.pad' part, the parameter of (3), is the max size/length to convert to (number less than 100, three digits), the Number (2) length is tested against size, if less than size it adds a '0' at beginning. Number.prototype.pad = function(size) Edited May 25, 2018 by dsonesuk Link to comment Share on other sites More sharing options...
iwato Posted May 25, 2018 Author Share Posted May 25, 2018 Dsonesuk. thank you, but I am only unclear about that part of the implementation that encloses the number 2 in parentheses. Why is the number two enclosed in parentheses? Roddy Link to comment Share on other sites More sharing options...
dsonesuk Posted May 25, 2018 Share Posted May 25, 2018 Number is a wrapper object and specifically deals with numeric or numeric strings. Number.prototype will represent a prototype for Number constructor that is a function (.pad =function(size){...}) to manipulate the object Number i.e (2) value passed to it. So if you create (2) Number object belonging to prototype constructor Number.prototype.pad=function(size){...} (2).pad(3) This will use these object and argument values to initialise this specific constructor (Number.prototype.pad=function(size)) for number manipulation and return the result. Link to comment Share on other sites More sharing options...
justsomeguy Posted May 25, 2018 Share Posted May 25, 2018 That's called syntactic sugar. Doing "2.method" would result in a syntax error, because a scalar value like that isn't actually an object (don't quote me on that - I don't know how it works under the hood specifically, but I suspect that Javascript treats literal scalar values differently than their object counterparts). When you put the value in parentheses it makes the value an expression, and an expression is allowed to have properties and methods and things like that. So, these are functionally equivalent: (2).method(); var num = new Number(2); num.method(); I don't think it's technically correct to say it "converts the number to an object", but they are at least functionally equivalent. Link to comment Share on other sites More sharing options...
Ingolme Posted May 25, 2018 Share Posted May 25, 2018 (edited) As far as I know, numbers in Javascript are natively objects, everything is an object actially. There's just a syntax problem when doing 2.method() because the meaning of the dot is ambiguous until reading further, it could be indicating a decimal point. This works in the Javascript console: var x = 5; x.toString(); // Prints "5" Edit: There is actually some kind of distinction between primitives and the object representations of them, but anytime you call a method on a primitive the Javascript engine automatically creates an object representation of it. This MDN document has a short section about it. While the document is talking about strings it applies to all primitives. Edited May 26, 2018 by Ingolme Link to comment Share on other sites More sharing options...
iwato Posted May 26, 2018 Author Share Posted May 26, 2018 So, in conclusion, .pad(size) is a user-created method of a primitive Number object that is called via the Number.prototype property and executed by either the parentheses operator or variable assignment. Do I have everyone's agreement. Roddy Link to comment Share on other sites More sharing options...
justsomeguy Posted May 29, 2018 Share Posted May 29, 2018 pad is a method which is added to all Number objects via the prototype. Changing an object's prototype is how you add properties or methods to all instances of that object. Link to comment Share on other sites More sharing options...
iwato Posted May 29, 2018 Author Share Posted May 29, 2018 I understand the nuance, but I am now confused about the prototype property. Is it a single property with only one value, a single property with many values -- say, an array --, or something else. Roddy Link to comment Share on other sites More sharing options...
dsonesuk Posted May 29, 2018 Share Posted May 29, 2018 It can be any of those, depending on the object and its values you assign to it Link to comment Share on other sites More sharing options...
iwato Posted May 30, 2018 Author Share Posted May 30, 2018 Dsonesuk: Even something else? Roddy Link to comment Share on other sites More sharing options...
dsonesuk Posted May 30, 2018 Share Posted May 30, 2018 As a text string 'something else' sure. Link to comment Share on other sites More sharing options...
justsomeguy Posted May 30, 2018 Share Posted May 30, 2018 Think of the prototype as the blueprint from which objects are created, it contains all of the properties and methods that an instance of that object has. Javascript does not have classes like object-oriented languages, it is a prototype-based language. This is how it does that. Link to comment Share on other sites More sharing options...
dsonesuk Posted May 30, 2018 Share Posted May 30, 2018 <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" id="viewport" content="target-densitydpi=high-dpi,initial-scale=1.0"> <title>Document Title</title> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script> <script> //To specific Types Array.prototype.testArray = function() { //console.log(this.length); for (n = 0; n < this.length; n++) { console.log("ToArrayType : " + this[n]); } }; Number.prototype.testNumber = function() { var num = this; num = num / 2; console.log("ToNumberType : " + num); }; String.prototype.testString = function() { var join = this; join += " world!"; console.log("ToStringType : " + join); console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); }; //To non specific type function ArrayNonSpecificType(arr) { this.arr = arr; } function NumberNonSpecificType(num) { this.num = num; } function StringNonSpecificType(str) { this.str = str; } StringNonSpecificType.prototype.showString = function() { var join = this.str; join += " world Again!"; console.log("StringNonSpecificType : " + join); }; NumberNonSpecificType.prototype.showCalc = function() { this.num = this.num / 2; console.log("NumberNonSpecificType : " + this.num); }; ArrayNonSpecificType.prototype.showArray = function() { for (n = 0; n < this.arr.length; n++) { console.log("ArrayNonSpecificType : " + this.arr[n]); } }; //BY specific Type arrayObject = ["a", "b", "c", "d", "e"]; arrayObject.testArray(); (6).testNumber(); ("Hello").testString(); //By Non specific Type arrayObject2 = ["a", "b", "c", "d", "e", "a", "b", "c", "d", "e"]; arrayObject2 = new ArrayNonSpecificType(arrayObject2).showArray(); numberObject2 = new NumberNonSpecificType(9).showCalc(); stringObject2 = new StringNonSpecificType("Hello").showString(); </script> <style> </style> </head> <body> <div>Sorry nothing to see here! try viewing console.log</div> </body> </html> Link to comment Share on other sites More sharing options...
iwato Posted June 3, 2018 Author Share Posted June 3, 2018 Dsonesuk, I apologize for taking so long to return to this topic, but it was much more that I was expecting and required time to digest it. If I have understood correctly, its purpose is to show that everything in Javascript is indeed an object -- even functions. It is for this reason that one can even add a function to a function via the prototype property. Please confirm or disconfirm where appropriate. Roddy Link to comment Share on other sites More sharing options...
justsomeguy Posted June 4, 2018 Share Posted June 4, 2018 The purpose of a prototype is not illustrative, it's not to demonstrate something, it is how Javascript works. There is only one copy of a method like String.split, that function does not get copied to every String instance. There's just the one, and any time the split method is called on a string it runs that piece of code. Programmers use the prototype for several things, including adding new properties or methods to existing objects. Link to comment Share on other sites More sharing options...
dsonesuk Posted June 5, 2018 Share Posted June 5, 2018 Almost everything in JavaScript is an object, by constructing a object you can control the properties it has, the values to those properties either by parameter passed to it, or pre-set these property values. The object construct functions function StringNonSpecificType(str) { this.str = str; this.str2 = "Say what?"; } create objects along with any properties associated with that specific object and at this moment it also becomes an parent object prototype. All child functions (methods) will have to refer to its constructed parent object prototype StringNonSpecificType.prototype.showString = function() { var join = this.str; join += " world Again!"; console.log("StringNonSpecificType : " + join); }; All the property values set in the parent prototype constructor are available to the child using this.xxx where 'xxx' refers to property name in that parent prototype. Initiating construct with argument value for property, stringObject2 = new StringNonSpecificType("Hello").showString(); associates a new specific object construct with argument value, and run specific method (function) associated specifically to that object parent construct to the variable stringObject2. Link to comment Share on other sites More sharing options...
iwato Posted June 6, 2018 Author Share Posted June 6, 2018 It is difficult for me to believe that I am still spending time to learn Javascript and PHP as subject material in and of themselves, but I am fascinated by language no matter its form, and these are especially useful languages. Indeed, I have recently discovered that jQuery can be incorporated into Javascript even at the prototype level. Please see below a functional example of this discovery. Indeed, a function is a function no matter where it is applied. Still, it is not quite that for which I was hoping (see question below). The HTML <body> <div id='test_array'>Can you see this?</div> </body> The Javascript Array.prototype.testArray = function() { //console.log(this.length); for (n = 0; n < this.length; n++) { console.log("ToArrayType : " + this[n]); $('#test_array').append($('<p></p>').html(this[n])); } }; arrayObject = ["a", "b", "c", "d", "e"]; arrayObject.testArray(); QUESTION: How would you replace the selector '#test_array' in such a way that the function testArray() would display its contents in the very place that it is invoked. The this pseudo variable does not work in this instance. Even the creation of a new, empty <div> tag fails. Roddy Link to comment Share on other sites More sharing options...
Ingolme Posted June 6, 2018 Share Posted June 6, 2018 Javascript does not work that way. If you want something to appear on the page you have to specify which element will contain it. The closest thing there is to display something where it is invoked is to use document.write(), but that has some serious side effects. You pretty much should never use it. Link to comment Share on other sites More sharing options...
justsomeguy Posted June 6, 2018 Share Posted June 6, 2018 Indeed, I have recently discovered that jQuery can be incorporated into Javascript even at the prototype level. Is that surprising? As has been pointed out, jQuery is not separate from Javascript. It is not a different language. It is Javascript code. So, yes, you can use Javascript code in Javascript. The this pseudo variable does not work in this instance. Of course it does, it refers to the object instance, just like with any other prototype. the function testArray() would display its contents in the very place that it is invoked. You want an array to display its contents in the middle of your code? That's where you invoke a method, inside the code, so where exactly are you trying to display the contents? Link to comment Share on other sites More sharing options...
dsonesuk Posted June 6, 2018 Share Posted June 6, 2018 Did that code actually work? also what do you mean by creation of empty div? there is no creation of empty div? I produced different example of what you might mean <div id='test_array'>Can you see this? 1111111</div> <div id='test_array2'>Can you see this? 222222</div> <!-- the 3rd is created through array prototype --> Array.prototype.testArray = function() { //$('#test_array').empty(); //use to empty original childNodes including text for (n = 0; n < this.length; n++) { $('#test_array').append('<p>' + this[n] + '</p>'); } $('#test_array').append('<hr>'); }; Array.prototype.testArray2 = function() { this.join = ""; for (n = 0; n < this.length; n++) { this.join += '<p>' + this[n] + '</p>'; } $('#test_array2').html(this.join); $('#test_array2').append('<hr>'); }; /* */ Array.prototype.testArray3 = function() { this.newElem = document.createElement("div"); this.newElem.id = "test_array3"; this.parentElem = document.body; this.parentElem.appendChild(this.newElem); for (n = 0; n < this.length; n++) { $('#test_array3').append('<p>' + this[n] + '</p>'); } $('#test_array3').append('<hr>'); }; initialisation //BY specific Type arrayObject1 = ["a", "b", "c", "d", "e"]; arrayObject2 = ["a", "b", "c", "d", "e", "f"]; arrayObject3 = ["a", "b", "c", "d", "e", "f", "g", "h"]; arrayObject1.testArray(); arrayObject2.testArray2(); arrayObject3.testArray3(); Link to comment Share on other sites More sharing options...
iwato Posted June 7, 2018 Author Share Posted June 7, 2018 JSG: Yes, jQuery is Javascript, but it is specially wrapped Javascript, and I am still trying to understand the prototype object and use of the prototype property. Ingolme: Yes, I have used document .write() many times in my own notes, because I tire quickly of the alert( ) function. When the document is properly opened and closed the side effects that you mentioned can be avoided. I was hoping that jQuery would allow me to get around having to use it. Dsoneuk: Yes, your .testArray3( ) function works as far as the vertical structure of the document is concerned, but it simply ignores the CSS context into which it is inserted. Could this be avoided by assigning as a parent element something more specific than that of the document's body? If so, how would one go about selecting a named, rather than a generic element? If no, what would you suggest. Roddy Link to comment Share on other sites More sharing options...
dsonesuk Posted June 7, 2018 Share Posted June 7, 2018 <div id="specificID">Sorry nothing to see here! </div> Array.prototype.testArray4 = function(idref = "test_array4", parentElemID = document.body) { this.idref = idref; this.newElem = document.createElement("div"); this.newElem.id = this.idref; this.parentElem = parentElemID; this.parentElem.appendChild(this.newElem); for (n = 0; n < this.length; n++) { $('#' + this.newElem.id).append('<p>' + this[n] + '</p>'); } $('#' + this.newElem.id).append('<hr>'); } arrayObject4 = ["a", "b", "c", "d", "e", "f", "g", "h"]; arrayObject4.testArray4(undefined, document.getElementById("specificID")); // OR // var x=document.getElementById("specificID"); // arrayObject4.testArray4(undefined, x); // (inner parent id, outer parent id) //arrayObject4.testArray4("newidref", document.getElementById("specificID")); Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now