美文网首页
prototype 属性

prototype 属性

作者: KrisLeeSH | 来源:发表于2017-07-05 15:10 被阅读12次

prototype 属性使您有能力向对象添加属性和方法。

JavaScript中的每个对象都有prototype属性,对对象的prototype属性的解释是:返回对象类型原型的引用

A.prototype = new B();

相当于把B的方法和属性拷贝一遍到A,当然,非覆盖的。

es6前的类

es6之前是js中是没有class的,所以创建类时我们使用:

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

    this.sayHi = function () {
        console.log("Hi, I'm " + this.name + "!");
    }
};

var person = new Person("Li Lei");  // 创建实例
person.sayHi();  // 调用实例方法

这时候 Person 就是一个类对象了,function 即构造方法。

类方法、对象方法与原型方法

var Person = function (name) {
    this.name = name;
    
    this.sayHi = function() {  // 对象方法
        console.log("Hi, I'm " + this.name + "!");
    }
};

Person.run = function() {  //类方法
    console.log("I can run");
}

Person.prototype.sayHiInChinese = function() {  //原型方法
    console.log("我的名字是" + this.name);
}

//测试
var p1=new Person("Han Meimei");
p1.sayHi();
Person.run();
p1.sayHiInChinese(); 

原型方法和对象方法的调用首先需要先创建类的实例,并且只能通过类的实例调用。

prototype与属性方法调用

简单来说,寻找实例方法的顺序是:先找自身有没有属性方法,有的话调用,没有的话在prototype原型链上找,找到即调用
比如:

function baseClass()
{
  this.showMsg = function()
  {
     alert("baseClass::showMsg");   
  }
}

function extendClass()
{
}

extendClass.prototype = new baseClass();
var instance = new extendClass();
instance.showMsg(); // 显示baseClass::showMsg

如果extendClass中存在与baseClass同名的方法,baseClass不会覆盖掉extendClass中的同名方法:

function baseClass()
{
    this.showMsg = function()
    {
        alert("baseClass::showMsg");   
    }
}

function extendClass()
{
    this.showMsg =function ()
    {
        alert("extendClass::showMsg");
    }
}

extendClass.prototype = new baseClass();
var instance = new extendClass();

instance.showMsg();//显示extendClass::showMsg

如果想要调用baseClass中的方法,可以使用call

extendClass.prototype = new baseClass();
var instance = new extendClass();

var baseinstance = new baseClass();
baseinstance.showMsg.call(instance);  //显示baseClass::showMsg

相关文章

网友评论

      本文标题:prototype 属性

      本文链接:https://www.haomeiwen.com/subject/mmgfhxtx.html