javascript中有prototype属性,我了解到的有两种用法:

一、prototype可以给对象动态的添加属性或者方法,如:

<script>
    function student(stuname,age,classname){
        this.stuname = stuname;
        this.age = age;
        this.classname = classname;
    }
    var stu1 = new student("yovan",21,"软件七班");//实例化学生对象
    student.prototype.php_score = null;//利用prototype给student中添加一个php_score属性
    stu1.php_score = 99;
    console.log(stu1.php_sorce);//99
</script>

二、prototype可以做到类似Java继承那样,如:

<script>
    function mytest1(parameter){
        this.testNum = parameter;
   };
   function mytest2(parameter){
        this.testString = parameter;
   };
    //用mytest2的prototype去实例化mytest1,继承了mytest1里面的testNum属性
    mytest2.prototype = new mytest1(2017); 
    var objectTest2 = new mytest2("hello");
    console.log(objectTest2.testString+","+objectTest2.testNum);//hello,2017

</script>


Logo

前往低代码交流专区

更多推荐