您的位置:首页 > Web前端 > Node.js

node.js js this指针自我总结

2016-01-31 23:30 691 查看
个人是这么认为的,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"}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: