RN知识RN 项目使用组件

Reacg-Native call apply

2019-02-15  本文已影响8人  精神病患者link常

更加详细的请看这篇文章

this.aaaa = 1234;

function add(a,b)
        {
            console.log('add:a=',a);
            console.log('add:b=',b);

// 内部的this 
            console.log('add:this=',this);

            console.log('this.aaaa=',this.aaaa)

            alert(a+b);
        }
     
        add.call(this,1,1); // 将函数内部的this改变,指向当前this
        //add.apply(this,[1,1])
image.png
 let abc = {
            a: 1111,
            b: 2222
        };

        function add(a,b)
        {
            console.log('add:a=',a);
            console.log('add:b=',b);

            console.log('add:this=',this);
            console.log('add:this.a=',this.a);
            console.log('add:this.b=',this.b);


            alert(a+b);
        }
        
        add.call(abc);// add函数内部的this指向abc
image.png
add.call(1,1,1); // 第一个参数就是函数内部的this指向,不可随便填写
image.png
 let a = {
            p1: 100,
            p2: 200,
            add: function () {
                console.log('this=',this)
                alert(this.p1 + this.p2)
            }
        };

        let b = {
            p1: 300,
            p2: 100,

        };

        a.add.call(b)
        // 可以理解为a中想获取b中的数据进行操作
        // 也可以理解为b的参数想实现a中的方法

image.png

在 javascript 中,call 和 apply 都是为了改变某个函数运行时的上下文(context)而存在的,换句话说,就是为了改变函数体内部 this 的指向。

apply()方法 接收两个参数,一个是函数运行的作用域(this),另一个是参数数组。

call()方法 接收参数,一个是函数运行的作用域(this),其他是一一列举出来的参数。

image.png

使用实例

假如A页面要调用B页面的方法,在B方法内部还想使用A的数据
在A中

B.func.call(this)

index.js

export default class Page extends Component {
    constructor(props) {
        super(props);
        this.userName = '尼古拉斯';
    }
    render() {
        return Render.render.call(this);
    }
}

render.js

export default {
    render() {
        let userName = this.userName; // 当前this指向A,可以获得A中的数据
        return (
           <View>...</View>
        )
    }
}

获取数组中的最大值和最小值

// 数组没有max方法,但是Math有,可以借助Math的方法进行比较
var numbers = [50, 234 , 742 , -80 ]; 
var maxNumber = Math.max.apply(Math, numbers),   //742
var maxNumber = Math.max.call(Math,50, 234 , 742 , -80); //742
上一篇 下一篇

猜你喜欢

热点阅读