0

There was zero explanation about this in the book I'm reading. They just threw an example with this, and didn't bother to explain anything at all.

I keep testing and experimenting with this in an attempt to infer what it is and how it works exactly, and most of all, how is this different from just creating a new variable and then assigning a function to it.

Is the only difference just the fact that, you can use 'this' keyword with the String.prototype, because the String variable to which it has to be attached to becomes the parent object?

What I don't get it, what exactly are you creating? Are you creating a new method? Property? value? Just a function that can contain a value or some statement to be executed, and then you assign that function to .. a new String? Why do I need to assign the new function to a String in order to run it? If I just target the name of the function, it won't work. It has to attached to a String variable to execute the function. Why?

String.prototype.more = function() {
    var confirm2 = 2 + 2;
    return confirm2;
}

alert(more());

I can't create a new function and then try to run it without either writing the whole name "String.prototype.more()", or first creating a new variable, and then attaching the name "more" to it, and then the function is triggered.

Can somebody explain to me does String.prototype.something = function() {} create a new function and assign it to the 'something', and it could just contain a retuned value or a statement waiting to get executed? If so, how is this different from just creating a new variable and doing the same thing? Is the only difference the fact that you can use 'this' keyword? Why do I need to attach the function name to a String in order to run it? Am I not understanding something important here?

happy_story
  • 1
  • 1
  • 7
  • 17
  • 1
    Good JavaScript tutorial here: https://javascript.info/ especially take a look at "Prototypes, inheritance" there. – Jesper Feb 02 '21 at 13:09
  • You should read this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain – Liam Feb 02 '21 at 13:12
  • It is like you kept one apple inside the box and asking why i can't access the apple outside it? – Suresh Ponnukalai Feb 02 '21 at 13:13
  • JavaScript's Prototypal inheritance allows you to arbitrarily add functionality to an existing type. Here, the example adds a function, called `more` to the `String` type. Because this has been added to a string you'll need to call it like `'a string value'.more()` – phuzi Feb 02 '21 at 13:14
  • You've asked about a dozen questions in this question. Good questions ask one. See [ask]. For the answer to this question, see (among others) [How does JavaScript .prototype work?](https://stackoverflow.com/q/572897/215552) – Heretic Monkey Feb 02 '21 at 13:20
  • I've already read about inheritance, and I feel that I understand how prototype work. But ONLY when attached to objects. I've learned how to use prototype to assign new properties and methods to new object that I've created, or attach entire new construction functions to a new object. But I am confused about this because this is not a new object, but a String variable. So, is the String variable treated like an object here? – happy_story Feb 02 '21 at 13:26
  • Are you asking why primitives like strings and numbers are able to access methods like objects? Primitives are actually converted to objects at runtime and discarded (autoboxing). – adiga Feb 02 '21 at 14:13
  • @phuzi `"abc" instanceof String` returns false – adiga Feb 02 '21 at 14:22
  • You can read more about here:[javascript: do primitive strings have methods?](https://stackoverflow.com/questions/5751704) and [Why, in JavaScript, does '3 instanceof Number' == false, but '3..method()' will call Number.prototype.method?](https://stackoverflow.com/questions/40491240) – adiga Feb 02 '21 at 14:22

2 Answers2

2

you can Use the prototype property to add a new property to all objects of a given type , in your example you are trying to add new property to the string type :

 String.prototype.more = function() {
        var confirm2 = 2 + 2;
        return confirm2;
    }
    alert('example'.more());
    //that will allert 4
Belhadjer Samir
  • 1,461
  • 7
  • 15
1

JavaScript is a little weird in some aspects compared to other programming language.

  1. JavaScript functions are full objects. In other languages functions are language constructs. For example if you create a function like this
function example1() {}

what you are really doing is creating an object of type function to the root object (which is the window object in your browser)

function example1() {}
console.log(window.example1) // function example1() {}
console.log(typeof window.example1) // function
  1. Every object template in JavaScript has a prototype. So when you want to check for a function or a value of an object (hence called property), and that object doesn't have that property, JavaScript examines the prototype of that object, if the property is there. If that is not the case, JS will climb up the prototype ladder until it finds that property or reaches the end of the ladder (which is the object template)

In your case: String is the template object, if you create a string

// A is created as a new String
A = "a"
// The constructor of string is the String object which is a native function
console.log(String) // function String() { [native code] } 
console.log(typeof String) // function
console.log(A.constructor === String) // true

// The String function has a prototype which contains all the functions of the String "class"
console.log(String.prototype) // function
// The method `sub` of the A object is in fact the method `sub` of the `String.prototype`
// that means A doesn't have the method sub for itself, but uses the 
console.log(A.sub === String.prototype.sub) // true
// There are some other wild things going on that include `__proto__` and `constructor` properties.
console.log(String.prototype.__proto__.constructor === Object) // true

Regarding your case

String.prototype.more = function() {
  var confirm2 = 2 + 2;
  return confirm2;
}


a = "" // `a` is created as string has now a __proto__ property that points to String.prototype

// Following three are all the same
console.log(a.more) // more doesn't exist, but the more method of the prototype is used
console.log(a.__proto__.more) // `a.__proto__` is a reference to `String.prototype`
console.log(String.prototype.more)

Edit 1

Some more general examples

console.clear()
a = new Object()

// a now has automatically been assigned a `constructor` property, which is the `Object` function
console.log(a.constructor) // function Object() 

// the Object function has a `prototype` property, which is an object
console.log(typeof Object.prototype) // object

// a is assigned a `__proto__` property, which is a reference to the `prototype` property of its `constructor`
console.log(a.__proto__ === a.constructor.prototype) // true

// a has inherited a method `hasOwnProperty` which tells us, if a property is directly on the object or is inherited from the prototype chain

console.log(a.hasOwnProperty('myNewProperty')) // false
a.myNewProperty = 'this is my own'
console.log(a.hasOwnProperty('myNewProperty')) // true

// Here you can see: `a` doesn't have the property `hasOwnProperty`, but the `__proto__` (which is `Object.prototype`) has
console.log(a.hasOwnProperty('hasWonProperty')) // false
console.log(a.__proto__.hasOwnProperty('hasOwnProperty')) // true
yunzen
  • 32,854
  • 11
  • 73
  • 106
  • Is it correct to simply say that the String is treated as an object to which you are attaching a new function, which can be either a property or a method depending on what it contains? So if that's the case, then obviously you can't access the property or method outside the object. That would make sense if it were the case. – happy_story Feb 02 '21 at 13:37
  • I admit, it's all a bit confusing.at first. Since newer version of JavaScript you can use the `class` keyword. But this is only syntactic sugar for the prototype chain – yunzen Feb 02 '21 at 13:53