前陣子在做JavaScript的異常處理時,意外的發現一些實體判定的問題。
考慮如下的程式:
try {
throw( 'Exception' );
} catch( e if e instanceof String ) {
alert( e );
}
這樣是不會捕捉到異常的,就算'Exception'這個字串可以使用String的method,就算typeof的取值是string。
接著再進一步的試驗:
也就是說new運算子才是產生instance,其他的都算literal。
var temp = [ 'test', String( 'test' ), new String( 'test' ) ];
for( var x in temp ) {
alert( temp[x] + ', ' + typeof( temp[x] ) + ', ' + ( temp[x] instanceof String ) );
}
// test, string, false
// test, string, false
// test, object, true
可以看見只有用new才會真正用constructor建造一個實體,不加new的話似乎只是呼叫function而已。也就是說new運算子才是產生instance,其他的都算literal。
可是要說instance和literal不一樣嗎?好像也不盡然:
String.prototype.popup = function() {
alert( this );
};
// will alert 'test'
'test'.popup();
沒有留言:
張貼留言