javascript 继承 constructor 须要注意点

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>

</body>
<script>
    var People = function(){
        this.name = "Jackey";
    };
    People.prototype.getName = function(){
        return this.name;
    };

    var Man = function(){
        this.sex = "male";
        People.call(this);
    };
    //缺点 ,name 是父类中的属性,若是修改会影响子类
    //Man.prototype = People.prototype;
    //new 新开内存
    Man.prototype = new People();
    Man.prototype.constructor = Man;//可随意修改People的属性,不会影响到Man

    var man = new Man();
    console.log(man.getName());

</script>
</html>
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>

</body>
<script>
    var People = function(){
        this.name = "Jackey";
    };
    People.prototype.getName = function(){
        return this.name;
    };

    var Man = function(){
        this.sex = "male";
        People.call(this);
    };
    //缺点 ,name 是父类中的属性,若是修改会影响子类
    //Man.prototype = People.prototype;
    //new 新开内存
    Man.prototype = new People();
    Man.prototype.constructor = Man;//可随意修改People的属性,不会影响到Man

    var man = new Man();
    console.log(man.getName());

</script>
</html>
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>

</body>
<script>
    var People = function(){
        this.name = "Jackey";
    };
    People.prototype.getName = function(){
        return this.name;
    };

    var Man = function(){
        this.sex = "male";
        People.call(this);
    };
    //缺点 ,name 是父类中的属性,若是修改会影响子类
    //Man.prototype = People.prototype;
    //new 新开内存
    Man.prototype = new People();
    Man.prototype.constructor = Man;//可随意修改People的属性,不会影响到Man

    var man = new Man();
    console.log(man.getName());

</script>
</html>
相关文章
相关标签/搜索