zoukankan      html  css  js  c++  java
  • 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();
  • 相关阅读:
    python的数据类型+常用操作符
    厉害了
    git merge ignore line ending
    CNAME , DNS , A Record , Domain Name

    setcookie无效
    magic quote gpc htmlspecialchars
    整型 浮点型 不能转化
    git push -f带来的conflict如何解决
    git pull --rebase
  • 原文地址:https://www.cnblogs.com/binfire/p/2880523.html
Copyright © 2011-2022 走看看