# 来看一看这个面试题

### 1、实现一个阶乘

``````function factorial (n){
return n>1 ? factorial(n-1)*n : 1;
}复制代码``````

### 2、说一下深拷贝和浅拷贝

``````function deepCopy(obj) {
var objArray = Array.isArray(obj) ? [] : {};
if(obj && typeof obj ==="object"){
for(key in obj){
if(obj.hasOwnProperty(key)){
//如果obj的子元素是对象，递归操作
if(obj[key] && typeof obj[key] ==="object"){
objArray[key] = deepCopy(obj[key]);
}else{
//如果不是直接赋值
objArray[key] = obj[key]
}
}
}
}
return objArray;
}

var s1 = {
num:10
}

var objs=deepCopy(s1);
objs.num=11;
console.log(s1.num);
console.log(objs.num);

jquery的extend方法也可以实现深拷贝

``````JQuery.extend([deep],target,object1,[objectN])
var obj1 = {
num:100
}
var obj2=\$.extend(true,{},obj1);
obj2.num=11;
console.log(obj1.num);
console.log(obj2.num);

``````var test = {
name:{
first:'刘',
second:'张'
},
age:32,
friend:['老王','老李','老孙']
}

var result = JSON.parse(JSON.stringify(test));
result.age=50;
result.friend.push('小张');
console.log(test);
console.log(result);复制代码``````

### js原生插件的几种常用写法

``````function createPerson(name, age, job) {
var o = new object();
o.name = name;
o.age = age;
o.job = job;
o.sayName = function (){
}
return o;
}

var person = createPerson("老王",30,'Doctor')复制代码``````

``````var createPerson=(function () {
function sayName(name) {
console.log(name);
}
return{
log:sayName
}
})();
createPerson.log("老王")复制代码``````

``````function Person() {

}
Person.prototype.name = '老王';
Person.prototype.sayName = function () {
console.log(this.name);
}

var personOne = new Person();
personOne.sayName()

``````function Person(name, age, job) {
this.name = name;
this.age = age;
this.job = job;
}

Person.prototype = {
constructor : Person,
sayName : function () {
console.log(this.name);
}
}

var personOne = new Person('老王', 30, 'Doctor');
personOne.sayName()复制代码``````

### JQuery插件写法

``````//创建
\$.extend({
insertHello:function (dom) {
\$(dom).html("Hello World")
}
})
//引用
\$.insertHello('#hello')
})复制代码``````

``````(function (\$) {
\$.fn.setModelUI = function (options) {
let defaults = {
time : 100 ,
name : "老王",
age  : 30
}
var options = \$.extend(defaults, options);
this.each(function () {
console.log(options.name);
})
}
})(jQuery);

})复制代码``````

### 4、说一下本地缓存

sessionStorage：存储特定于某个会话的数据，也就是说该数据只能保持到浏览器关闭。存储大小为5M，有自己的存储方法（setItem,getItem）,存储的是对象，以键值对的方式存储。

localStorage：永久保存客户端数据，存储大小和方式与sessionStorage相同。