一般我们的原型写法都是
var Father = function () { this.speed= 90; }; Father.prototype.move = function (speed) { console.log("原型"+speed); }; Father.prototype.start = function () { console.log(this.speed); }; var father = new Father(); father.start();//90
如果我们要在start里面调用move这个方法
直接用this指针就行了
var Father = function () { this.speed = 90; }; Father.prototype.move = function (speed) { console.log("原型"+speed); }; Father.prototype.start = function () { //console.log(this.speed); this.move(this.speed); }; var father = new Father(); father.start();//原型90
如果我们在start里面再写一个function,看下怎样
var Father = function () { this.speed = 90; }; Father.prototype.move = function (index) { console.log("原型"+index); }; Father.prototype.start = function () { //console.log(this.name); //this.move(this.speed); setInterval(function () { this.move(this.speed);
}, 2000); }; var father = new Father(); father.start();//error
出现错误,会提示不存在move属性或方法,为什么呢
初步认为是setInterval里面的匿名函数,指针this没有指向外面的move,再修改一下
var Father = function () { this.speed = 90; }; Father.prototype.move = function (index) { console.log("原型"+index); }; Father.prototype.start = function () { //console.log(this.name); //this.move(this.speed); setInterval(function (self) { self.move(self.speed); self.speed++; }, 2000,this); //setInterval(function () { }, 2000); }; var father = new Father(); father.start();//在chrome下正常运行,但是在IE下就不行了
我们把this指针传进去
var Father = function () { this.speed = 90; return Father.prototype; }; Father.prototype.speed = 100; Father.prototype.move = function (speed) { console.log("原型" + speed); }; Father.prototype.move1 = function (speed) { return function () { this }; } Father.prototype.start = function () { //console.log(this.name); //this.move(this.speed); //setInterval(function () { //self.move(self.speed); //this.move(this.speed); //self.speed++; //return this; //}, 2000); //setInterval(function () { }, 2000); //(function adds(self) { //console.log("ddd"); //self.move("ddddddd"); //})(this); //function adddd(self) { // self.move("hh"); //}; //adddd(this); var self = this; setInterval(function () { self.move("ddddddddddddddddddddddddddd"); }, 2000); }; var father = new Father(); father.start();//原型
搞掂
javascript 面向对象--理解,布布扣,bubuko.com
原文:http://www.cnblogs.com/lihaozhou/p/3645255.html