面向对象

继承(原型链) a-->b-->c
1、扩展原型对象
往原型对象中添加新属性,实例也可以共享,Person.prototype.say=function(){};
2、替换原型对象
把默认的原型对象替换掉,Person.prototype={constructor:Person,p1:function(){}等多个属性}
3、混入继承(extend)
将一个对象的功能(属性.方法)拷贝到另一个对象中
封装函数function extend(target,source){
for(var key in source){
var value=source[key];
target[key]=value;
}
return target;
}
4、混入+原型继承(extend(Person.prototype))
往原型对象中扩展多个方法
混入继承函数中的target参数就是原型对象,source就是{a:function(){},b:function(){}}类似这样的对象

5、经典继承(create()/Object.create())
创建一个对象,让这个对象继承自另一个对象
最早是由道格拉斯在蝴蝶书<javascript语言精粹>中提出的
封装函数,只需导入另一个对象,本来的对象作为返回值返回
function create(o2){
function F(){}
F.prototype=o2;
return new F();
}
ES5(IE9+)直接有方法Object.create(o2);
能力检测
if(Object.create){
o=Object.create(o2);//IE9+的方法
}else{
o=create(o2);//封装的函数
}


原型链:
几乎所有的属性都有__proto__,除了Object.prototype
prototype是任何函数都具有的属性
constructor(可读可写的属性,可删,少用):函数的原型对象

function Car(){}
var bmw=new Car();
1、console.log(Car.prototype.constructor);//Car
2、bmw.__proto__跟哪个对象全等 //Car.prototype
3、Car.prototype.__proto__跟哪个对象全等 //Object.prototype
4、Car.__proto__跟哪个对象全等 //Function.prototype
5、Car.constructor跟哪个对象全等 //Function(自己没有,到自身的__proto__中去找)
6、Function.__proto__ //Function.prototype
7、Object.__proto__ //Function.prototype
8、Object.constructor //Function
9、Function.constructor //Function
10、Object.prototype.constructor //Object

eval:
eval与函数的区别
eval("var a=10;console.log(a);")只能执行一段代码(无法重复执行),声明的是全局变量,多用会造成全局变量污染
函数var f0=new Function("var b=30;console.log(b)"),可以重复执行一段代码,函数本身是一个局部作用域,里面变量是局部变量
eval推荐使用的场景,用来解析JSON数据,不推荐用来执行大量JS数据
"use strict"严格模式,阮一峰ES5里面的,ie9以下不支持
严格模式下,变量声明必须有var ,给eval里面的语句独立开辟了作用域中,eval里面的变量相当于在一个盒子里,外界无法访问
www.ruanyifeng.com
eval解析对象时要注意给字符串添加前后小括号,因为大括号可以有两种含义:表示对象,还可以表示代码块
var json="{'name':'张三','age':18,'gender':'男'}";
console.log(eval("("+json+")"));
var json2="[{'name':'张三','age':18,'gender':'男'}]";
console.log(eval(json2));


静态属性是函数本身定义的属性(属性定义在函数对象内存中)
实例属性:(构造)函数实例上面定义的属性
function Student(){
this.age=18;
}
var s1=new Student();
s1.gender="男";
Student.ccc="123";

其中age和gender是实例属性
ccc是静态属性,还有可以查看控制栏name,
length:形参的个数,
caller:表示函数由哪个函数调用,如果当前函数不是在某个哈数内部调用,那么caller的属性值就是null
arguments
prototype
__proto__等

arguments主要用来存储函数的实参(就像数组一样,通常把它称为伪数组)
arguments有一些属性length,0,1,2,callee(arguments.callee的值指向函数本身===)
arguments[1];表示获取第二个属性
fn.length表示形参个数,arguments,length表示实参个数
伪数组:一个对象不是Array函数创建出来的,但是它拥有一些属性0,1,2,length,可以让我们使用for循环进行遍历
var o={0:10,1:20,2:30,length:3};可以通过for循环遍历,伪数组

递归:
斐波那契数列
function fib(n){
i++;
if(n<=0) return;
if(n===1||n===2) return 1;
return fib(n-1)+fib(n-2);
}
console.log(fib(100));
阶乘n!
function factorial(n){
if(n<0) return;
if(n===0) return 1;
return factorial(n-1)*n;
}
console.log(factorial(10));

递归查找元素(检测一个元素是不是另一个元素下面的元素)
function find(child,parent){
if(child.parentNode==null) return false;
if(child.parentNode===parent) return true;
return find(child.parentNode,parent);
}
console.log(find(d3,d1));
chrome浏览器中,会把页面中的id的元素存储为全局变量

原文地址:https://www.cnblogs.com/sw1990/p/5911208.html