一、(6分)
實(shí)現(xiàn)type函數(shù)用于識(shí)別標(biāo)準(zhǔn)類型和內(nèi)置對(duì)象類型,語(yǔ)法如下:
var t = type(obj);
使用舉例如下:
var t = type(1) // t==="number"
var t = type(new Number(1)) // t==="number"
var t = type("abc") // t==="string"
var t = type(new String("abc")) // t==="string"
var t = type(true) // t==="boolean"
var t = type(undefined) // t==="undefined"
var t = type(null) // t==="null"
var t = type({}) // t==="object"
var t = type([]) // t==="array"
var t = type(new Date) // t==="date"
var t = type(/\d/) // t==="regexp"
var t = type(function(){}) // t==="function"
解:
/*方法一:識(shí)別標(biāo)準(zhǔn)類型和內(nèi)置類型的*/
function type(obj){
return obj.prototype.toString.call.slice(8,-1);
}
/*方法二:識(shí)別所有類型*/
function type(obj){
if(obj){
return obj.constructor.toString().match(/function\s*([^(]*)/)[1]
}else{
return Object.prototype.toString.call(obj).slice(8,-1)
}
}
二鹃栽、(10分)
ES5中定義的Object.create(proto)方法穿扳,會(huì)創(chuàng)建并返回一個(gè)新的對(duì)象,這個(gè)新的對(duì)象以傳入的proto對(duì)象為原型借尿。
語(yǔ)法如下:
Object.create(proto) (注:第二個(gè)參數(shù)忽略)
proto —— 作為新創(chuàng)建對(duì)象的原型對(duì)象
使用示例如下:
var a = Object.create({x: 1, y: 2});
alert(a.x);
Object.create在某些瀏覽器沒(méi)有支持刨晴,請(qǐng)給出Object.create的兼容實(shí)現(xiàn)。
解:
Object.create=Object.create||function(obj){
var F=function(){};
F.prototype=obj;
return new F();
}
var a = Object.create({x: 1, y: 2});
console.log(a.x);
三路翻、(10分)
高版本的firefox,chrome及ie10以上的瀏覽器實(shí)現(xiàn)了Function.prototype.bind方法狈癞,bind方法調(diào)用語(yǔ)法為:
functionObj.bind(thisArg[, arg1[, arg2[, ...]]])
使用范例參考如下:
function move(x, y) {
this.x += x;
this.y += y;
}
var point = {x:1, y:2};
var pointmove = move.bind(point, 2, 2);
pointmove(); // {x:3, y:4}
但是低版本瀏覽器中并未提供該方法,請(qǐng)給出兼容低版本瀏覽器的bind方法的代碼實(shí)現(xiàn)茂契。
解:
Function.prototype.bind=function(obj){
var aa=this, args=arguments;
return function(){
aa.apply(obj,Array.prototype.slice.call(args,1))
}
}
function move(x, y) {
this.x += x;
this.y += y;
}
var point = {x:1, y:2};
var pointmove = move.bind(point, 2, 2);
pointmove();
console.log(point);
// {x:3, y:4}
四蝶桶、(10分)
斐波那契數(shù)列(Fibonacci Sequence)由 0 和 1 開始,之后的斐波那契數(shù)就由之前的兩數(shù)相加掉冶。在數(shù)學(xué)上真竖,斐波那契數(shù)列是以遞歸的方法來(lái)定義的:
請(qǐng)實(shí)現(xiàn)一個(gè)函數(shù),參數(shù)為n厌小,返回結(jié)果為以n為下標(biāo)的斐波那契數(shù)疼邀。函數(shù)語(yǔ)法為
var num = fibonacci(n);
使用舉例如下
var num = fibonacci(3); // num值等于2
var num = fibonacci(5); // num值等于5
解:
function fibonacci(n){
if(n==0){
return 0;
}else if(n==1) {return 1;
}
else{return (arguments.callee(n-1)+arguments.callee(n-2));}
}
var num = fibonacci(3);
console.log(num);//2
var num = fibonacci(5);
console.log(num);//5