面向对象

133 阅读2分钟

面向对象的三种创建方法

1. 构造函数法去创建对象

function info(name1,age1,college1) {
       this.name = name1;
       this.age = age1;
       this.college = college1;
       this.show = function () {
           alert(name1 + ";" + age1);
       }
   }
   var test = new info("小灰灰",1);
   test.show();
//通过原型法去添加新的属性
info.prototype.sex = “男”;
console.log(test.sex);-----返回  男

2. 工厂模式去创建对象

最重要的是要return obj 对象

function Student() {
        var obj = new Object();
        obj.name = "打得出";
        obj.age = 21;
        obj.sing = function (song) {
            alert(this.name + song);
        };
        return obj;
    }
    var stu = new Student();
    stu.sing("谁")

3. 原型法

function creatObj() {
        creatObj.prototype.name = "szczdsc";
        creatObj.prototype.age = 12;
        creatObj.prototype.show = function () {
            alert(this.name);
        }
    }
    var person = new creatObj();
    person.show();


  • 原型法和构造函数相结合
利用原型法添加属性和对象(方法)---也可以给内置对象添加方法

你的构建的对象.原型.新的属性 = “”
你的构建的对象.原型.新的方法 = function (参数1,参数2...){
     (this.参数1 = 参数1;
     this.参数2 = 参数2;)
     return 参数1 + 参数2;

}

function info(name1,age1,college1) {
       this.name = name1;
       this.age = age1;
       this.college = college1;
       this.show = function () {
           alert(name1 + ";" + age1);
       }
   }
   //添加新的属性
   info.prototype.sex = "nan";
    alert(test.sex);
    
    //添加新的方法
   info.prototype.add = function (start,end) {
    this.start =  start;
    this.end = end;
    return start + end;

};

   
   var test = new info("小灰灰",1);
   alert(test.add(1,2));
   test.show();
  • 比较字符串
字符串与字符串的比较是比的是首字母的ASCII码,按位比(第一位相同比第二位)
0-9 A-Z(65-90) a-z(97-122)

var name1 = "csac";
   var name2 = "kjhccc";
   var name = name1 > name2 ? "true" : "false";
   alert(name);------------------falsealert("5" > "10");-------true

字符串与数字比较,他会先把字符串转化成成数字,然后在进行比较
首先,将字符串字母parseInt,只要字符串中有字母就得出NAN,然后,222与NAN比较,总是得出false

alert(222 < "a112");-----------false
alert(parseInt("a112"));---------NANalert(222 > "112a");--------------false

alert(222 > "abc");-----false
alert(222 < "abc");-----false
  • 子节点(几种方式)

firstChild---找到第一个,如果有空格的话,就是找到空格,返回text
fistElementChild-----找到第一个,跳过空白
children----找到所有孩子,比较奈斯,兼容性极好
childNodes----返回数组