javascript原型和原型链

<script type="text/javascript">
    //原型
    var Test = function() {};
    
    //Test对象本身的方法
    Test.sayHello = function() {
        alert('Hello, Test!');
    };
    
    //Test实例化对象的方法
    //函数对象会有一个prototype属性,指向这个函数的原型对象,原型对象相当于一个类
    Test.prototype.sayHello = function(){
        alert('Hello, Test prorotype!');
    };
    
    var obj = new Test();
    obj.sayHello();  //调用Test.prototype.sayHello
    Test.sayHello(); //调用Test.sayHello
    
    //原型链
    function Student() {}
    Student.prototype.sayHello = function() {
        alert("Hello, I'm a student!");
    }
    
    function CollegeStudent() {}
    //设置CollegeStudent的prototype属性为Student的实例对象
    CollegeStudent.prototype = new Student();
    CollegeStudent.prototype.property = 'college student';
    //修改CollegeStudent.prototype.constructor为CollegeStudent本身
    CollegeStudent.prototype.constructor = CollegeStudent;
    
    //创建CollegeStudent的一个实例
    var s = new CollegeStudent();
    //s对象从CollegeStudent.prototype和Student.prototype继承属性和方法
    alert(s.property);
    s.sayHello();
    
    //当查找一个对象的属性时,会遍历原型链,一直往顶层Object找,如果没有找到,则返回undefined。
    /*
    s [CollegeStudent的实例]
        CollegeStudent.prototype [Student的实例]
            Student.prototype
                Object.prototype
    */
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值