js面向对象开发基础

js的面向对象开发能力较弱,基本是以prototype为核心的面向对象,虽然现在出了个class这玩意,但本文还是先不做探讨。

面向对象基础——构造函数方法

var Fly = function (speed) {
    this.power = "i can fly";
    this.speed = speed+"km/h";
    this.init = function(){
        console.log(" i will fly and my speed is "+this.speed);
    }
}
var plane = new Fly(1000)
plane.init()

 至此我们便构建出了一个简单的对象plane是一个 new Fly();

那么我们想要拓展怎么办

面向对象实现的基础——prototype

Fly.prototype.sayPower = function(){
    console.log(this.power)
}

由此我们便给他添加了一个新的方法叫做sayPower();同样可以在plane中调用。

一个一个的添加非常麻烦,要添加好多那么应该怎么办

 

Fly.prototype = {
    type:"波音747",
    saySpeed:function(){
        console.log(this.speed)
    },
    sayType:function(){
        console.log(this.type)
    }
}

 

我们调用了一个对象指向了他的prototype,但是这是我们执行plane.sayPower()会发现这个方法是没有的,因为他被后来的覆盖了

constuctor指向

上面那种方法还有一个问题就是指向变了,指向就是plane的构造者,plane.constructor变成了Object();

所以我们应该加一行

Fly.prototype = {
    constructor:Fly,
    type:"波音747",
    saySpeed:function(){
        console.log(this.speed)
    },
    sayType:function(){
        console.log(this.type)
    }
}

JQuery中的链式实现方法

神奇的jQuery实现了链式调用的原理就是在不要求返回特定值时一直返回本身

(function (){
    var jQuery = function(selector){
            return new Obj(selector)
        }//创建一个对象
    var Obj = function (selector){
            this.init(selector)
        }//创建时这个对象初始化一个方法
    Obj.prototype = {
        length:0,
        constructor:jQuery,
        init:function(selector){
            var elem;
            elem = document.querySelectorAll(selector);
            for(var i=0;i<elem.length;i++){
                this[i] = elem[i];
            }
            this.length = elem.length;
            return this  //初始化的时候会返回一个本身,然后创建一个hash数组
}, css:function(attr,value){ for(var i=0;i<this.length;i++){ this[i].style[attr] = value; } return this  //遍历自己的hash,给添加样式 } } window.$ = window.jQuery = jQuery })(); $(".box").css("background","#f93")

还有一种神奇的方法

 

(function (){
    var jQuery = function(selector){
            return new jQuery.prototype.init(selector)
        }
    jQuery.prototype = {
        length:0,
        constructor:jQuery,
        init:function(selector){
            var elem;
            elem = document.querySelectorAll(selector);
            for(var i=0;i<elem.length;i++){
                this[i] = elem[i];
            }
            this.length = elem.length;
            return this
        },
        css:function(attr,value){
            for(var i=0;i<this.length;i++){
                this[i].style[attr] = value;
            }
            return this
        }
    } 
    jQuery.prototype.init.prototype = jQuery.prototype //在这里都连起来
    window.$ = window.jQuery = jQuery
})();
$(".box").css("background","#f93")

 

posted @ 2017-02-02 15:39  白与小寒  阅读(209)  评论(0编辑  收藏  举报