js 面向对象中的函数相互之间如何调用

JavaScript012

js 面向对象中的函数相互之间如何调用,第1张

用Function.prototype.bind即可

比如this.ele.addEventListener('touchstart', this.selectmouse.bind(this))

定义在Dumplings.prototype里的函数如果作为Dumplings实例的方法调用,其this指针会指向Dumpling实例。

但作为参数传递给其他函数(比如addEventListener)时其this指针会被重置,由addEventListener控制。

你需要在prototype里的函数里调用其它同级的函数,this就应当指向Dumplings实例,用this.ele来绑定事件和访问事件的对象,这样才能通过this来访问其他同级对象。为防止addEventListener改变this的指向,需要用bind固定下来。

<script>

var s1 = { 

    callS2: function(){

        alert(s2.hello())

    },

    hello : function(){

        return "s1"

    }

}

var s2 = { 

    callS1: function(){

        alert(s1.hello())

    },

    hello : function(){

        return "s2"

    }

}

s1.callS2()

s2.callS1()

</script>

var o = {a:"abc",b:{c:function(param){alert(this.a)//这里的this指向的不是o而是b,所以this是没有a属性的,这里应该弹出undefinedalert(param) }},d:function(){this.b.c.call(this,'dddd')//这样就行了,就可以改变this的指向为d的this}}