• Javascript面向对象谈


    一:创建对象:

     //对象封装原始模式
            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();
  • 相关阅读:
    智能家居项目(3):编译工具makefile
    9、Cocos2dx 3.0游戏开发找小三之工厂方法模式与对象传值
    Redis于windows在安装
    Gray Code -- LeetCode
    hdu 1575 Tr A(矩阵高速电源输入)
    phpstorm快捷键
    Reverse Linked List II -- LeetCode
    程序猿的故事-注定奉献给节目
    poj2112 Optimal Milking --- 最大流量,二分法
    POJ 3356 AGTC(最长公共子)
  • 原文地址:https://www.cnblogs.com/binfire/p/2880523.html
Copyright © 2020-2023  润新知