zoukankan      html  css  js  c++  java
  • 自己理解的javascript 的对象和类理解

    首先需要先理解类和对象的意义,我个人理解如下:

    类:对象的抽象化;

    对象:类的实体;

    javascript中没有class关键字和类的用法,只能用伪类来做类的,所以要用function来定义累的名字;

    如:

    function myClass(){

    this.name="张三";

    }

    这样myClass方法才能用原型连接 prototype;这样才能扩展此类;

    也可以用 new myClass();这个类

    javascript中有对象,简单的写法就是 

    var obj={name:"张三"}

    因为obj本身就是一个对象,不能实例化(即不能用new关键字);

    我自己从网上找了几个相关例子,自己也写了写,在此粘出代码希望可以更好的理解

    var Person=(function(){
        function Person(){
            this.name='person';
            this.age=18;
            this.init=function(name,age){
                this.name = name;
                this.age = age;
            }
        }
        Person.prototype={
                k:function(){
                    alert(this.name)
                },
                s:function(){
                    alert(this.age)
                }
        }
        return Person;
    })();
    
    var Dog = (function(){
        function Dog(){
            this.name='dog';
            this.age=11;
        }
        return Dog;
    })();
    
    var p = new Person();
    //p.k();
    p.init('张三',70)
    //p.k();
    delete p.name;
    
    
    Dog.prototype = Person.prototype;
    Dog.prototype.init=function(name,age){
        this.name = name;
        this.age=age;
    }
    var d = new Dog();
    //d.k();
    
    Object.extend=function(destination,source){
        for(property in source){
            destination[property]=source[property];
        }
        return destination;
    }
    Object.prototype.extend = function(object){
        return Object.extend.apply(this,[this,object])
    }
    
    function Rect(){
        
    }
    //Rect.prototype=(new Person).extend({
    //    add:function(){
    //        alert('add');
    //    },
    //    show:function(){
    //        alert('show')
    //    }
    //});
    
    //var r = new Rect();
    //r.show();
    //r.k();
    
    function JC(){
        
    }
    var j = new JC();
    j.extend({
        a: function(){
            alert('a');
        },
        d:function(){
            alert('d');
        }
    });
    j.a();
  • 相关阅读:
    Java 课程设计:LWZ
    回溯法解骑士巡游问题
    2021.3.30 错误2
    2021.3.29 关于上下滚动
    2021.3.28 WebView的用法
    2021.3.27 关于错误1
    2021.3.26 Python创建表
    2021.3.25 人月神话阅读笔记06
    2021.3.24 个人作业第三阶段1
    2021.3.23 个人作业第三阶段
  • 原文地址:https://www.cnblogs.com/tongchuanxing/p/4234339.html
Copyright © 2011-2022 走看看