第一部分:Object Prototypes (对象原型)
(1)定义一个方法,要求传入一个string类型的参数,然后将string的每个字符间加个空格返回,例如:
spacify('hello world') // => 'h e l l o w o r l d'
实现方案:
function spacify(string){ return string.split('').join(' '); } console.log(spacify('hello world')); //h e l l o w o r l d
(2)如何把(1)中定义的方法放入String对象的前面调用,例如:
'hello world'.spacify();
这里主要考察对function prototypes(方法原型)的理解,将此方法添加到String对象的原型上:
String.prototype.spacify = function(){ return this.split('').join(' '); }; console.log('hello world'.spacify()); //h e l l o w o r l d
拓展考点:解释一下函数声明和函数表达式的区别
对于函数声明,js解析器会优先读取,确保在所有代码执行之前声明已经被解析,而函数表达式,如同定义其它基本类型的变量一样,只在执行到某一句时也会对其进行解析,所以在实际中,它们还是会有差异的,具体表现在,当使用函数声明的形式来定义函数时,可将调用语句写在函数声明之前,而后者,这样做的话会报错。
第二部分:参数 arguments
(1)先说说自己对参数(arguments)对象的理解。
arguments 对象只是与数组类似(它并不是Array 的实例),具有length属性用来检测传递参数的个数。 函数arguments对象
(2)定义一个未定义的log方法,用来代理处理console.log方法。
log('hello world')
容易想到的方法:
function log(msg) { console.log(msg); }
如果要求改变调用log的方式,传入多个参数,并且传入参数的个数是不定得,这里需要使用apply方法。解释一下apply和call的区别(接收参数形式的不同)。
function log(){ console.log.apply(console, arguments); } log('hello', 'world','beijing', 1); //hello world beijing 1
(3)给每一个log消息添加一个"(app)"的前辍,比如:
'(app) hello world'
arugments是一个伪数组,需要将他转化成为标准数组。通常方法是使用Array.prototype.slice方法。
function log(){ var args = [].slice.call(arguments); //[] 等价于 Array.prototype args.unshift('(app)'); console.log.apply(console, args); //apply方法可以接收数组作为参数 } log('hello', 'world'); //(app) hello world
第三部分:上下文和this
(1)给出以下例子,注意count属性不是只读取当前上下文的。求出以下的输出结果。
var User = { count: 1, getCount: function() { return this.count; } };
console.log(User.getCount()); //1 var func = User.getCount; console.log(func()); //undefined
下面一个得出undefined的原因是func是在winodw的上下文中被执行的,所以会访问不到count属性。
(2)怎么样保证User总是能访问到func的上下文,即返回正即的值:1
应该使用Function.prototype.bind方法,例如:
var func = User.getCount.bind(User); console.log(func()); //1
但是bind方法对老版本的浏览器不起作用时怎么去解决?有没有替代方法。
Function.prototype.bind = Function.prototype.bind || function(context){ var self = this; return function(){ return self.apply(context, arguments); }; }
参考来源: 如何面试前端工程师:GitHub 很重要