Domanda

Per quanto ne so non è possibile modificare un oggetto da solo in questo modo:

String.prototype.append = function(val){
    this = this + val;
}

Quindi non è affatto possibile lasciare che una funzione stringa si modifichi da sola?

È stato utile?

Soluzione

Le primitive String sono immutabili, non possono essere modificate dopo che vengono creati.

Ciò significa che i caratteri al loro interno non possono essere modificati e che qualsiasi operazione sulle stringhe crea effettivamente nuove stringhe.

Forse vuoi implementare una specie di generatore di stringhe?

function StringBuilder () {
  var values = [];

  return {
    append: function (value) {
      values.push(value);
    },
    toString: function () {
      return values.join('');
    }
  };
}

var sb1 = new StringBuilder();

sb1.append('foo');
sb1.append('bar');
console.log(sb1.toString()); // foobar

Altri suggerimenti

Mentre le stringhe sono immutabili, il tentativo di assegnare qualsiasi cosa a this in qualsiasi genera un errore.

Ho fatto la stessa ricerca ... Prima di tutto, ovviamente non puoi semplicemente fare questo + = x, 'this' è un oggetto, non puoi usare l'operatore + sugli oggetti.

Esistono metodi "dietro le quinte" che vengono chiamati, ad esempio

String.prototype.example = function(){ alert( this ); }

sta effettivamente chiamando

String.prototype.example = function(){ alert( this.valueOf() ); }

Quindi quello che devi trovare è un valore rilevante che fa il contrario - qualcosa come this.setValue (). Solo che non ce n'è uno. Lo stesso vale anche per Number.

Anche i metodi integrati sono vincolati da quello

var str = 'aaa';
str.replace( /a/, 'b' );
console.log( str ); // still 'aaa' - replace acts as static function 
str = str.replace( /a/, 'b' );
console.log( str ); // 'bbb' - assign result of method back to the object

Su alcuni altri oggetti puoi; ad esempio in una data:

Date.prototype.example = function(){
 this.setMonth( this.getMonth()+6 );
};
var a=new Date();
alert(a.getMonth());
a.example();
alert(a.getMonth());

È fastidioso, ma il gioco è fatto

Le stringhe sono immutabili; quello che stai chiedendo è come dire, " Perché non posso fare:

Number.prototype.accumulate = function (x) {
    this = this + x;
};

... "?

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top