原型的一些知识

普通调用函数,若函数没有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

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值