http 关于node.js中用的this

在不同语言中,this的用法基本都一样的,是指函数或者对象本身

js中this的指向是可以用call或者apply改变的

var pet ={
	words:'...',
	speak:function(say){
		console.log(say+' '+this.words)
	}
}
//pet.speak('Speak')

//指定dog为pet的this
var dog={
	words:'Wang'
}
pet.speak.call(dog,'Speak')

pet.speak中this并不是本身的pet,而是指向dog,输出结果是Speak Wang

进一步扩展

function Pet(words){
	this.words=words
	this.speak=function(){
		console.log(this.words)
	}
}

function Dog(words){
	Pet.call(this,words)
	//Pet.apply(this,arguments)
}

var dog=new Dog('wang')
dog.speak()

个人笔记,错误请指出

猜你喜欢

转载自blog.csdn.net/weixin_41427294/article/details/81436722