变量的原型链和this的指向

来源:互联网 发布:淘宝精装修教程pdf 编辑:程序博客网 时间:2024/06/05 00:50
var ob = 5;
function test(){
    console.log('构造函数完成');
    this.test2 = function(){
        console.log(ob);
    };
};
var hua =new test(); // 构造函数完成. 构造时会执行test().
hua.test2(); // 5
在构造函数过程中,函数中的变量ob会在本身函数的作用域中找ob,没有的话就会跳到上一个函数作用域
链,直到window的作用域链当中,找不就报undifined。
=================================================
var ob = 5;
function test(){
    console.log('构造函数完成');
    this.test2 = function(){
        console.log(this.ob); //this 指向的是 hua = new test(),这个对象。
    };
};
var hua =new test(); // 构造函数完成. 构造时会执行test().
hua.test2(); // undefined

=================================================
function test(){
    this.ob = 5;
    console.log('构造函数完成');
    this.test2 = ()=>{
        console.log(this.ob); //this 指向的是 hua = new test(),这个对象。
    };
};
var hua =new test(); // 构造函数完成. 构造时会执行test().
hua.test2(); // 5

=================================================
this.ob = 5;
function test(){
    console.log('构造函数完成');
    this.test2 = function(){
        console.log(this.ob); //this 指向的是 hua = new test(),这个对象。
    };
};
var hua =new test(); // 构造函数完成. 构造时会执行test().
hua.test2(); // undefined

=================================================
function test(){
this.ob = 5;
console.log('构造函数完成');
    this.test2 = ()=>{
        console.log(this.ob); //this 指向的是 hua = new test(),这个对象。
    };
};
var hua =new test(); // 构造函数完成. 构造时会执行test().
hua.test2(); // undefined

=================================================
在构造函数中使用原型对象      
比直接在构造函数中写的效率要高的多
Person.prototype.sayName= function(){
    console.log(this.name);
};
但是如果方法比较多的话,大多人会采用一种更简洁的方法:直接使用一个对象字面形式替换原型对象,如下
Person.prototype ={
    sayName :function(){
        console.log(this.name);
    },
    toString :function(){
        return "[Person "+ this.name+"]";
    }
};
=================================================
var ob=5;
function test(){
    this.test2 = function(){
        console.log(ob); // 5
    };
};
var hua = new test();
hua.test2();
function foo() {
  console.log(this.a)
}
var a = 3;
foo() // 3

var obj = {
  a: 2,
  foo: foo
}
obj.foo() // 2
以上两者情况 this 只依赖于调用函数前的对象,优先级是第二个情况大于第一个情况

var c = new foo()
c.a = "c";
console.log(c.a);

还有种就是利用 call,apply,bind 改变 this,这个优先级仅次于 new
=================================================
var jin = {
    ni:'你好',
    sayName:function(){
        console.log("靳腾华:"+this.ni);
        function hua(){
            console.log(this);
        }
        hua();
    }
}
jin.sayName();
// =================================================
var a = {
    name: 'js',
    log: function() {
        console.log(this)
        function setName() {
            this.name = 'javaScript';
            console.log(this);
        }
        setName()
    }
}
a.log()
setName 中的 this 指向了 window,很多人认为他应该是指向 a 的。这里其实我们不需要去管函数是写在什 么地方的,我们只需要考虑函数是怎么调用的,这里符合上述第一个情况,所以应该是指向 window。
原创粉丝点击