js的原型链继承

与其他普通函数建立相比,构造函数建立时需要用 new 进行声明:

var f =  new Foo()

new一个对象的过程: 1.创建一个新的对象,2.this指向这个新对象,3.执行函数,4.返回this

function Foo(name) {
            this.name = name;
            console.log(this);  // Foo {name: ""}

            // return this;   
            // 默认有这一行
}

Foo此时具有了一个为__proto__的属性,一般称为隐式原型。

而每一个函数都包含有一个prototype属性,称为显示原型。这个属性指向引用的原型对象,可以通过__proto__来访问这个属性。当将函数用作构造函数时,新创建的对象会从原型对象上继承属性。

一个简单的原型链如下:

构造函数构造的所有新对象可以通过__proto__访问构造函数的prototype属性。

下面是一个原型链继承的例子:

<div class="prototype"></div>
function Element (name) {
        this.name = document.getElementsByClassName(name)[0];
 }

Element.prototype.html = function(html) {
        var name = this.name;
        if(html) {
            name.innerHTML = html;
            return this;
        } else {
            return name.innerHTML;
        }
}
Object.prototype.click = function(type,fn) {
        var name  = this.name;
        name.addEventListener(type,fn);
        return this;
}
var elem = new Element("prototype");
elem.html("<p>原型链</p>");
elem.click("click",function() {
        alert("这是原型链继承");
});

猜你喜欢

转载自www.cnblogs.com/LJ96/p/11111918.html