0
我在編寫需要在原型中引用this
的代碼,但它不能作爲函數。 Javascript不會讓我這樣做,但它看起來像數組和字符串的屬性做到這一點。我知道length
是內置的,我的代碼不是,但如果可以,我該如何實現這一點?長度屬性如何工作?
我想:
String.prototype.prototypeName = (function(aThing){
//Do whatever I need to do here
})(this);
但是,全局對象的引用,因爲this
調用的函數之外。
String.prototype.prototypeName = function(aThing){
//Do whatever I need to do here referencing this
};
但是,這是一個函數,我不能這樣做。
我不能有一個函數,因爲用戶可以調用該函數並使用typeof
就可以了,原型應該返回一個字符串。 例如:
String.prototype.reverse = "Put something that is the reversed string (or this)";
console.log("Stuff"); //"ffutS"
console.log("Anything"); //gnihtynA
使用getter https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get –
「*在原型中引用它,但它不能是一個函數*」,「」 *原型應該返回一個字符串*「 - 什麼?請顯示你如何使用你要求的東西的預期結果。 – Bergi
不,不可能重新實現'.length'在數組上做什麼。 – Bergi