怎样修改原型对象prototype

修改原型对象的方法分为两种情况, 一种是对原型对象的属性方法做增删改, 一种改变原型对象的指向.

第一种: 对原型对象的属性/方法做增删改

function Person(name){
    this.name = name;
}

var lilei = new Person("Lilei");

//
Person.prototype.getName = function (){
    return this.name;
}
lilei.getName(); // "Lilei"

//
Person.prototype.getName = function(){
    return this.name.toUpperCase();
}
lilei.getName(); // "LILEI"

//
delete Person.prototype.getName; // true
lilei.getName(); // Error

第二种: 改变原型对象的指向

以下代码中, 我们如果要整个改变原型对象的指向, 那目标对象中必须要有一个constructor属性, 值为这个原型对象关联的构造函数. 此外, 这个改变不能对已生产的实例对象作更改, 比如下面的lilei, 我们在修改以后调用lilei.sayHello()还是会报错.

function Person(name){
    this.name = name;
}

var lilei = new Person("Lilei");

var overridePrototype = {
    constructor: Person,
    sayHello: function(){
        return "Hello, I'm " + this.name;
    }
};

// lilei.sayHello(); // Error

Person.prototype = overridePrototype ;
// lilei.sayHello(); // Error

var hanmeimei = new Person("Hanmeimei");
hanmeimei.sayHello(); // "Hello, I'm Hanmeimei"
原文地址:https://www.cnblogs.com/aisowe/p/11672032.html