RN中的this机制

一 :四种绑定规则

优先级由高到低顺序
1:new 绑定

var o = {
    m: function(){
        return this;
    }
}
var obj = new o.m();//obj为新产生的对象
console.log(obj,obj === o);//{} false
console.log(obj.constructor === o.m);//true

2:显示绑定
通过call apply bind实现

var a = 0;
function foo(){
    console.log(this.a);
}
var obj1 = {
    a:1
};
var obj2 = {
    a:2
};
foo.call(obj1);//1
foo.call(obj2);//2

3:隐式绑定

function foo(){
    console.log(this.a);
};
var obj1 = {
    a:1,
    foo:foo,
}
//foo()函数的直接对象是obj1,this隐式绑定到obj1
obj1.foo();//1

4:默认绑定

//虽然test()函数被嵌套在obj.foo()函数中,但test()函数是独立调用,而不是方法调用。所以this默认绑定到window
var a = 0;
var obj = {
    a : 2,
    foo:function(){
            function test(){
                console.log(this.a);
            }
            test();
    }
}
obj.foo();//0

二:箭头函数绑定

箭头函数的绑定规则只与作用域有关,箭头函数会继承外层函数调用的this绑定

三:函数嵌套

函数嵌套中内部和外部函数相互独立调用没有this继承关系,
方法嵌套内部方法会继承外部函数的this指向。

function f3() {
    console.log('f3 this',this);//全局对象
}

export default class Page1 extends Component {
    constructor(props){
        super(props);
    }

    test=()=>{
         //箭头函数内部指向Page1  class
        console.log('test this',this);
        let obj={
            f1:function () {
                console.log('obj f1 this',this); // 指向obj
                function f() {
                    console.log('obj f this',this);
                }
                f();   //函数的嵌套不存在this的继承 内部f和外部f1 相互独立 因此内部f全局对象 外部f1指向obj对象
                f3();//内嵌的函数不存在this的继承关系 因此调用f3的是全局对象
                this.f2(); //方法的嵌套是可以继承this的 即内部的方法可以继承外部方法的this
            },
           f2:function () {
                console.log("obj f2 this",this)
            }
        }
        obj.foo();
    };

    test2(){
        //不是箭头函数 指向调用它的对象这里为touch组件
        console.log('test2 this',this);
        // this.countdown();//报错
    }
    countdown(){
      console.log('countdown this',this);
    }

    render(){
        return (
            <View style={styles.container}>
                <TouchableOpacity style={styles.touchstyle} activeOpacity={0.7} onPress={this.test}>
                    <View style={styles.viewstyle}>
                        <Text style={{fontSize:FONT(39/2),backgroundColor:'transparent',textAlign:'center'}}>test</Text>
                    </View>
                </TouchableOpacity>
                <TouchableOpacity style={styles.touchstyle} activeOpacity={0.7} onPress={this.test2}>
                    <View style={styles.viewstyle}>
                        <Text style={{fontSize:FONT(39/2),backgroundColor:'transparent',textAlign:'center'}}>test2 this指向touch组件</Text>
                    </View>
                </TouchableOpacity>
            </View>
        )
    }

参考:http://www.cnblogs.com/xiaohuochai/p/5735901.html

猜你喜欢

转载自blog.csdn.net/u014041033/article/details/80031641
RN