+ 10
Prototype Better Explained
I have recently seen the coding train make a video of which he uses ".prototype". I searched through the video and he has no attribute, method or object called prototype. After some research I realised it is built in in Javascript. So far NO tutorial has helped, Can someone explain it better please? I have made a code playing around with it. Keep in mind I have NO idea what I'm doing https://code.sololearn.com/W3P3J6RU4gA1/?ref=app
8 ответов
+ 9
https://code.sololearn.com/WJErVWqbo7SO/?ref=app
+ 7
Cont from previous msg...
We can build getEvenNumbersOnly prototype for the array.
To build the prototype function for array, we would use Array.prototype function, in the function, we use 'this' to refer the the calling array.
Array.prototype.getEvenNumbersOnly = function() {
var res = [];
for(var i=0;i<this.length;i++) {
if(this[i]%2===0) res.push(this[i]);
}
return res;
}
// For calliing the prototype from the array,
var nums = [1,2,3,4,5,6];
var evens = nums.getEvenNumbersOnly();
// Output: [2,4,6]
+ 7
🍹_JavaScripter_🍭{[#KeepCoding]}
Objects created by object-literal do not have the prototype function as a property. You need to create an object type by using an object constructor function.
https://www.w3schools.com/js/js_object_prototypes.asp
https://code.sololearn.com/WY9Do63zvMLO/#js
+ 5
☕__JavaScripter__💐
"Simply put, every function in JavaScript has a prototype property that references an object. " -Tyler McGinnis
https://tylermcginnis.com/beginners-guide-to-javascript-prototype/
Pretty easy to follow.
Suggestion: go to 9:13 min mark in video listen to the definition. Then go to the beginning of video.
+ 5
I learnt and understand JavaScript prototype from examples.
For example:
We need to build a function that only get the even numbers from an array.
We would likely write below function
function getEvenNumbersOnly (arr) {
var res = [];
for(var i=0;i<arr.length;i++) {
if(arr[i]%2===0) res.push(arr[i]);
}
return res;
}
var nums = [1,2,3,4,5,6];
var evens = getEvenNumbersOnly (nums);
// Output: [2,4,6]
cont.....
+ 2
https://code.sololearn.com/WL94G9kee3TF/?ref=app
Can someone explain why this won't work?
- 2
vr
c
- 4
How are you