JavaScript链式调用,对象属性与遍历,this指向,callee和caller

445 阅读1分钟

链式调用

var sched = {

wakeup: function(){

....

return this;

}

noon: function(){

....

return this;

}

night : function(){

....

return this; //是关键

}

}

链式调用:sched.wakeup().noon().night()

对象属性

obj["属性名"]

对象枚举


for in


hasOwnProperty


for in 会遍历出原型链上所有属性,hasOwnProperty可以判断是不是自身的属性

hasOwnProperty 排除原型链

A instanceof B A对象的原型里到底有没有B的原型,有就返回true

判断是否是数组的方法:

var a = [];

var str = Object.prototype.toString.call(a);

if(str === '[object Array]'){

console.log('是数组');

}else{

console.log('不是数组')

}


this


函数内部的this 运行以后指向window,若是实例化则指向实例化对象

call和apply的this

全局this->window

预编译函数this ->window

apply/call改变this指向

构造函数的this指向实例化对象

实例化的过程中 会var this = {__proto__:Test.prototype}


callee/caller


ex1:

function test(a, b, c){

console.log(arguments.callee.length); //3

console.log(test.length); //3

console.log(arguments.length); //2

}

test(1,2);


ex2:

var sum = (function(n){

if(n <= 1){

return 1;

}

return n + arguments.callee(n - 1);

})(100);

console.log(sum)


ex3:


caller

test1();

function test1(){

test2();

}

function test2(){

console.log(test2.caller); //返回当前被调用函数的函数引用

}

如果'use strict',caller、callee和arguments都不能通过