Prevent from type converting of "this" during a call to a function with apply
Servus Ninjas,
this is what ecmascript 5 spec. (page 118) in the section Function.prototype.apply(thisArg, argArray)
says:
NOTE: The thisArg value is passed without modification as the this value. This is a change from Edition 3, where a undefined or null thisArg is replaced with the global object and ToObject is applied to all other values and that result is passed as the this value.
This sounds promising, but this spec isn't implemented yet in any of the modern browsers so we开发者_开发问答 have to deal with the 3rd spec implementation.
My question now is „How to get the typeof
statement become TRUE?“
var foo = function (arg1, arg2) {
alert(typeof this == "string");
};
foo.apply("bar", ["arg1", "arg2"]);
any ideas?
There's 2 types of strings in JavaScript.
The ones with typeof string
"hello"
and the ones with typeof object
new String("hello");
apply
will always wrap any value you pass as an object since you need to use it through the this
keyword.
Either use this instanceof String
(same window-only) or use Object.prototype.toString.call(this) === "[object String]"
(works across windows).
The one and only thing at the moment is to check the type
with Object.prototype.toString.call(string) == "[object String]";
and convert this
back to String like:
var isString = function(string) {
return Object.prototype.toString.call(string) == "[object String]";
};
var isNumber = function(number) {
return Object.prototype.toString.call(number) == "[object Number]";
};
var toRightType = function(mess) {
if(isString(mess)) {
mess = mess+"";
}
if(isNumber(mess)) {
mess = mess+0;
}
return mess;
};
var foo = function () {
var _this = toRightType(this);
};
foo.apply("bar");
This is on of the sad chapters in javascript :(
精彩评论