[英]JavaScript Getters and Setters issue
這是我目前正在使用的代碼:
Object.defineProperty(String.prototype, "testy", {
get: function() {
return this.string;
},
set: function(string) {
this.string = string;
}
});
console.log("tessfef3t".testy());
在我使用String.prototype.testy = function {}
,但是有人告訴我,使用類似於上面的代碼的方法是更好的方法。 我不確定這是如何工作的,但是我還沒有該代碼工作。
有人可以告訴我如何正確地做我在做什么嗎?
謝謝
testy
是一種“偽”屬性-它沒有自己的值,但是設置或獲取其值將調用其set
和get
函數。 您可以像這樣使用它:
var foo = new String();
// this invokes the setter and sets foo.string to 5:
foo.testy = 5;
// this invokes the getter and prints the value of foo.string
console.log(foo.testy);
// this prints 5, because foo.string has been set by the setter
console.log(foo.string);
編輯:
現在,我看到您對您實際想要發生的事情的評論。 由於字符串是不可變的,因此無法更改字符串對象的值。 您必須銷毀字符串對象,然后將其替換為新對象,這在對象自己的成員函數中是不可能的。
如果您在getter和setter中所做的所有事情都是設置一個未在其他地方使用的屬性,並且沒有其他處理,那么使用getter和setter不會獲得任何好處,因此您最好使用原始方法。 此外,無論如何您將無法檢索在字符串上設置的屬性。 JavaScript中的字符串值(這是字符串文字(例如"foo"
創建的,並且是唯一一種通常有用的字符串)不是對象,因此嘗試訪問屬性需要特殊處理:有效地是一個臨時String
對象創建后立即丟棄。
最后,getter和setter的另一個主要缺點是它們在ECMAScript 5中指定,因此只能在相對較新的瀏覽器中使用。 例如,它們未在IE <9中實現。
這對我來說很好:
Object.defineProperty(String.prototype, "byteLength", {
get: function() {
var str = "" + this; // Get internal value
// Compute size in actual bytes vs Unicode characters
// per http://stackoverflow.com/a/23329386/912236
for (var b = str.length, c = str.length - 1; 0 <= c; c--) {
var a = str.charCodeAt(c);
127 < a && 2047 >= a ? b++ : 2047 < a && 65535 >= a && (b += 2);
56320 <= a && 57343 >= a && c--;
}
return b;
}
});
> "Hello".byteLength
< 5
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.