原型的一些知识

普通调用函数,若函数没有return语句,等于return undefined,

构造函数调用的时候,1创建一个新对象,2将构造函数的作用域赋给新对象(this赋给了这个新对象),3执行构造函数中的代码(为这个新对象添加属性),4返回新对象


function A(){
//1这一步是看不到的,创建一个新对象;
var a = {};
//2第二步赋给新对象。
this = a;
//3执行
alert(this);
//4返回新对象
return this;
}
A.prototype.a = 1;
console.log(new A().a);
function A() {

    alert(this);






    return {a: 'a'};
}
A.prototype.a = 1;
console.log(new A().a);
new A()与原型没关系,因为返回的不是this,是自己返回的对象的属性a;

,

  

  function Human() {
    }
    Human.prototype.address = {
        country: 'China',
        province: 'Zhejiang'
    };
    var h = new Human();
    h.address.country = 'US';

    alert(h.address.country);   //US,实例覆盖了原型,在实例上
    alert(h.address.province);  //Zhejiang,原型上
    alert(h.hasOwnProperty('address')); //false

  

h.address = {
        country: 'US'
    };
    delete h.address.country;
    delete h.address;

    alert(h.address.country);   //US,实例覆盖了原型,在实例上
    alert(h.address.province);  //Zhejiang,原型上
    alert(h.hasOwnProperty('address')); //false

  

function Human() {
    }
    Human.prototype.address = {
        country: 'China',
        province: 'Zhejiang'
    };
    var h = new Human();
    Human.prototype = {
        address: {
            a: 'aaa'
        }
    };
    var h2 = new Human();
    alert(h.address.country);   //China
    alert(h.address.province);  //Zhejiang
    alert(h.address.a);  //undefined
    alert(h2.address.country);  //undefined
    alert(h2.address.province); //undefined
    alert(h2.address.a);    //aaa

  

function test(h1) {
        h1 = {};
        h1.address = {
            a: 'aaa'
        };

//        address.a = 'bbb';
    }
    test(h);
    alert(h.address.country);   //China
    alert(h.address.province);  //Zhejiang
    alert(h.address.a); //undefined

  

var a = 'a';
    function test(a) {
        alert(a);   //a
        a = 'b';
        alert(a);   //b
        test2(a);
    }
    function test2(b) {
//        var a;
        alert(b);   //b
        alert(a);   //b
//        a = 'c';
        alert(a);   //c
    }
    test(a);

  

var getName;
function getName() {
    return 5;
}
function Foo() {
    getName = function () {
        return 1;
    };
    return this;
}
Foo.getName = function () {
    return 2;
};
Foo.prototype.getName = function () {

};
getName = function () {
    return 4;
};

//请写出以下输出结果:
console.log(Foo.getName());
console.log(getName());
console.log(Foo().getName());
console.log(getName());
console.log(new Foo.getName());
console.log(new Foo().getName());
var f = new new Foo().getName();
    alert(f);

  

原文地址:https://www.cnblogs.com/shenq/p/6359215.html