문제

내가 아는 한, 이런 식으로 객체를 수정하는 것은 불가능합니다.

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

그렇다면 문자열 함수가 스스로 수정하도록하는 것이 전혀 불가능합니까?

도움이 되었습니까?

해결책

그만큼 프리미티브는 불변이 아니며 만들어진 후에는 변경할 수 없습니다.

즉, 그 안의 캐릭터가 변경되지 않을 수 있으며 문자열의 모든 작업은 실제로 새로운 문자열을 만듭니다.

아마도 당신은 일종의 문자열 빌더를 구현하고 싶습니까?

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

다른 팁

줄은 불변하지만 할당하려고합니다 아무것 에게 this 안에 어느 클래스는 오류가 발생합니다.

나는 똑같이 연구하고있다 ... 우선, 물론 당신은이 + = x를 할 수 없다. '이것은'이 개체이다.

예를 들어 '장면 뒤에'방법이 있습니다.

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

실제로 전화를합니다

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

따라서 찾아야 할 것은 반대를 수행하는 관련 값입니다. 하나가 없다는 것을 제외하고. 숫자도 마찬가지입니다.

내장 방법조차도 그에 묶여 있습니다

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

다른 물체에서는 할 수 있습니다. 예를 들어 날짜에 :

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

짜증나지만 거기에 간다

줄은 불변입니다. 당신이 묻는 것은 "내가 할 수없는 이유 :

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

...?"

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top