Javascript面向对象谈

本文介绍了JavaScript中对象的创建方式,包括直接创建对象、构建类、使用Prototype进行方法和属性的扩展、通过Call/Apply实现继承,以及原型链的工作原理。

一:创建对象:

 //对象封装原始模式
        var Cat = {
            name: '',
            color: '',
            eat: function () { }
        };

        function eat() {
            console.log("test");
        }

        var cat1 = { name: "binfire", color: "red", eat: eat };

二:构建类:

 //对象封装
    function Cat(name, color) {
        this.name = name;
        this.color = color;
        this.eat = function () { console.log('eat fish'); };
    }

    var cat = new Cat("binfire", "red");
    cat.eat();

三:Prototype

  //js扩展方法和属性
    function Cat(name, color) {
        this.name = name;
        this.color = color;
    }
    Cat.prototype.type = "mammal";
    Cat.prototype.eat = function () { console.log("fk"); }

四:Call/Apply继承

 function Animal() {
        this.species = 'animal';
        this.sleep = function () { console.log('I\'m sleep at night'); };
    }

    //通过cat对象调用Animal
    /** @class Cat*/
    function Cat(name, color) {
        Animal.apply(this);
        this.name = name;
        this.color = color;
    }

    var cat1 = new Cat("binfire", "red");
    cat1.sleep();

五:原型链原理

    var Person = function () { };
    Person.prototype.Say = function () {
        console.log("person say");
    };

    var p = new Person();
    console.log(p.__proto__ == Person.prototype);
    //p没有Say方法,于是去_proto中找,也就是Person.propotype,
    //Person.propotype.Say
    p.Say();

1.var p={}; 初始化一个对象p
2.p.__proto__=Person.propotype;
3.Person.call(p); 构造p,初始化p

function Animal() {
    this.species = 'animal';
    this.sleep = function () {
        console.log('I\'m sleeping');
    };
}

function Cat(name, color) {
    this.name = name;
    this.color = color;
}
Cat.prototype = new Animal();
Cat.prototype.eat = function () { console.log("eating") };

var cat = new Cat("binfire", "red");
cat.sleep();

 

转载于:https://www.cnblogs.com/binfire/archive/2013/01/28/2880523.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值