Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
393 views
in Technique[技术] by (71.8m points)

javascript - Updating object value from prototype function

I'm trying to do this:

String.prototype.clear = function(){
    alert(this.value);
    this = ''; // I want to set value to '' here
}

var temp = 'Hello';
temp.clear();// After this step temp should be ''

But I'm getting invalid left hand assignment error. and I found this question as reference, but it's not really what I want. I also find out that 'this' is Immutable.

So, is there any way to do my task? I'm not using it any where. Just playing around. Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can create a class called MyMutableString like:

function MyMutableString(s) {
   this.string = s;
   this.clear = function() {
      this.string = "";
   }
}

Now you create an instance and use it like like:

var s = new MyMutableString("my str");
s.clear(); // makes string stored inside object `s` empty
console.log(s.string);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...