javascript深入了解(四)

来源:互联网 发布:梦龙网络计划64位win7 编辑:程序博客网 时间:2024/05/17 04:47


看下面一段函数声明:

function beginObject(){this.db=null;this.query="grant all privileges";(function doPack() {this.db="Connection";    console.log(this.db);})();}var parent=new beginObject();console.log(parent.db);console.log(parent.query);

//函数声明为类时,doPack自动执行,此时this.db为“Connection”,确实,控制台也确实输出的是“Connection”,但是当声明了类,并打印parent.db时,db仍然是初始值null


    为什么会这样呢?

    以此类推,也就是说,在javascript的继承中,子类继承的都应该是父类最初始话时的值,父类立即执行函数中的值不会被继承


    仔细想想,继承是不依赖具体对象的。但感觉还是很牵强:

    接下来声明一个函数Dog,去继承beginObject

function dog(){this.sx="dog";}dog.prototype=new beginObject();var test=new dog();console.log(dog.db);

    上面的代码输出的undefined,你的眼睛是不是亮瞎啦!更正dog为test,输出的是null。

    感觉还是不科学

    未完待续...

   


0 0
原创粉丝点击