js整理3

函数

  • call: fun.call(a), a会转化成相应的对象,函数内的this即指向它;
function foo() {
  console.log(this);
}
foo.call(null); //window
foo.call(undefined); //window

this

函数中this绑定

  • call-site: 函数的发起方
  • call-stack: 函数的执行栈
  • 如果函数没有明确的发起方,则其this有一个默认的绑定:全局
  • 在"use strict"模式下,如果函数的执行栈在该模式范围下,不会有默认的this绑定;否则没影响;
  • 隐性地失去绑定:因为真实的call-site不是原引用对象;
function foo() {
    console.log( this.a );
}

var obj = {
    a: 2,
    foo: foo
};

var bar = obj.foo; // function reference/alias!

var a = "oops, global"; // `a` also property on global object

bar(); // "oops, global"

...........
function foo() {
    console.log( this.a );
}

function doFoo(fn) {
    // `fn` is just another reference to `foo`

    fn(); // <-- call-site!
}

var obj = {
    a: 2,
    foo: foo
};

var a = "oops, global"; // `a` also property on global object

doFoo( obj.foo ); // "oops, global"
setTimeout( obj.foo, 100 ); // "oops, global"  原生自带的也是一样
  • 强行绑定:call, apply, bind和其他js内建的高级函数的参数定义上下文
function foo(el) {
    console.log( el, this.id );
}

var obj = {
    id: "awesome"
};

// use `obj` as `this` for `foo(..)` calls
[1, 2, 3].forEach( foo, obj ); // 1 awesome  2 awesome  3 awesome //第二参数传入
  • 当既有绑定又有new操作符的时候
function foo(p1,p2) {
    this.val = p1 + p2;
}

// using `null` here because we don't care about
// the `this` hard-binding in this scenario, and
// it will be overridden by the `new` call anyway!
var bar = foo.bind( null, "p1" );

var baz = new bar( "p2" );

baz.val; // p1p2
  • 总结
//有new操作符的时候,this指代newly constructed object;
//有绑定上下文的时候,指代绑定的上下文;
//当是对象方法的时候,指代那个对象
//默认情况下指代全局对象或者undefined(use strict)

属性

括号方式访问对象

  • 属性名都是字符串类型,不是字符串也会强制转化成字符串
var myObject = { };

myObject[true] = "foo";
myObject[3] = "bar";
myObject[myObject] = "baz";

myObject["true"];               // "foo"
myObject["3"];                  // "bar"
myObject["[object Object]"];    // "baz"

给对象添加属性

  • 注意数值字符串会隐式转化为数值
var myArray = [ "foo", 42, "bar" ];

myArray["3"] = "baz";

myArray.length; // 4

myArray[3];     // "baz"

对象复制

  • 简单的方法
var newObj = Object.create(someObj );
var newObj = JSON.parse(JSON.stringify( someObj));

对象枚举

  • 设置对象属性非枚举
var myObject = { };

Object.defineProperty(
    myObject,
    "a",
    { enumerable: true, value: 2 }
);

Object.defineProperty(
    myObject,
    "b",
    { enumerable: false, value: 3 }
);

for (var k in myObject) {
    console.log( k, myObject[k] );
}  // "a" 2

Object.keys( myObject ); // ["a"]

constructor和prototype

constructor

  • 它是由当前对象所引用的[[Prototype]]所决定
function Foo() { /* .. */ }
Foo.prototype.constructor === Foo

Foo.prototype = { /* .. */ }; // create a new prototype object

var a1 = new Foo();
a1.constructor === Foo; // false!
a1.constructor === Object; // true!     //[[Prototype]]实际是指向Object.prototype
Foo.prototype.constructor === Object

正则表达式

重复出现

?   可选 (添加后变非贪婪模式)
+   一次或多次
*    0次或多次
{n}  
{n,}
{,m}
{n,m}

反向引用

() 分组和捕获
[]  或操作符
/^([dtn])a\1/   \n表示匹配要引用的捕获数量
posted @ 2015-09-08 17:45  JinksPeng  阅读(184)  评论(0编辑  收藏  举报