node.js js this指针自我总结

                     个人是这么认为的,this在js里,谁调我,我就是谁,当然一些特殊的函数除外,比如call等等,下面贴上一段代码node.js实战一书的一段代码解释下,如果我说的不对,请指出,最近在学node.js!


var fs = require( 'fs' );

function FileObject ( ) {

	this.fileName = '' ;
	console.log("a_this : ",this);
	this.file_exists = function ( callback ) {
		console.log("b_this : ",this);
		console.log("About to open: " + this.fileName);
		fs.open(this.fileName,'r' ,function ( err, handle ) {
			if ( err ) {
				console.log("c_this : ",this);
				console.log("---------------------------------------------------");
				console.log("Can't open: " + this.filename);
				callback( err );
				return;
			}
			fs.close( handle, function(){} );
			callback(null,true)
		});
	}

}

var fo = new FileObject();
fo.fileName = 'file_that_does_not_exist';
fo.file_exists(function ( err, result){
	if( err ){
		console.log("Aw, bummer: " + JSON.stringify(err));
		return ;
	}
	console.log("file_exists!!!");
})



在上面的代码中有3个this  标签分别是a_this b_this c_this  以下简称 a  b c

对于a这个this  他的上一层函数是FileObject   我是这样理解的 ,谁调用了FileObject(), 在new FileObject(),其实会调用FileObject方法,类似与构造方法,这个this 其实是这个对象自己本身,


对于b这个this   fo调用了file_exists   那么它就是fo

对于c这个this   调用这个函数的其实一个匿名函数,这个函数是谁调用的呢,其实我是真的不知道,需要去看源码,

看fs.open();这个函数的实现,具体是谁调用了它,那么这个this就是它,所以这个this.filename 是undefined


不知道你看我的理解有没有对this有没有加深一些理解

反正就是这样,碰到this  你可以找谁调用了这个函数,那么这个this就是它,记得哦,是离它最近的那个函数!


顺便贴上这段代码的输出吧:

a_this :  FileObject { fileName: '' }
b_this :  FileObject {
  fileName: 'file_that_does_not_exist',
  file_exists: [Function] }
About to open: file_that_does_not_exist
c_this :  { global: [Circular],
  process:...(此处省了好多字)
}
---------------------------------------------------
Can't open: undefined
Aw, bummer: {"errno":-2,"code":"ENOENT","syscall":"open","path":"file_that_does_not_exist"}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值