JS-面向对象相关

  • onload 初始化 类似 构造函数初始化对象
  • 全局变量  ->  属性
  • 函数  ->  方法
  • 面向对象中最重要的就是 this的理解  this报错的原因  定时器的使用
function Aaa()
{
    var _this=this;
    this.a=1;
    
        //使用定时器  其中的this 指向window
    setInterval(function (){
        
        _this.show();
    }, 1000);
}

Aaa.prototype.show=function ()
{      
         //如果不定义_this,那么this.a调用的就是 window   
    alert(this.a);
};

window.onload=function ()
{
    new Aaa();
};           
  • Json方式 的面向对象
//相对简单 如果需要多个对象就不行了   比如 多点登录
var obj={a: 12, b: 5, c: function (){
    alert(this.a);
}};

obj.c();


var p1={
    name: 'blue',
    sex: '男',
    showName: function ()
    {
        alert('我的名字是:'+this.name);
    },
    showSex: function ()
    {
        alert('我的性别是'+this.sex+'的');
    }
};

p1.showSex();

JS本身是没有继承标准的  js也没有提供标准  所谓的继承就是 具备父级的属性和方法  开发者根据需要  实现自己需求  用了各种方法

 1 <?php
 2 // PHP中的继承
 3 class Person
 4 {
 5     function __construct($name, $sex)
 6     {
 7         $this->name=$name;
 8         $this->sex=$sex;
 9     }
10     
11     function showName()
12     {
13         echo $this->name;
14     }
15     
16     function showSex()
17     {
18         echo $this->sex;
19     }
20 }
21 
22 class Worker extends Person
23 {
24     function __construct($name, $sex, $job)
25     {
26         parent::__construct($name, $sex);
27         
28         $this->job=$job;
29     }
30     
31     function showJob()
32     {
33         echo $this->job;
34     }
35 }
36 
37 $w1=new Worker('blue', '男', '打杂的');
38 
39 $w1->showName();
40 $w1->showJob();
41 ?>
//js中的 一种继承写法
function Person(name, sex)
{
    this.name=name;
    this.sex=sex;
}

Person.prototype.showName=function ()
{
    alert(this.name);
};

Person.prototype.showSex=function ()
{
    alert(this.sex);
};

//-------------------------------------

function Worker(name, sex, job)
{
    //this->new出来的Worker对象
    //构造函数伪装        调用父级的构造函数——为了继承属性
    Person.call(this, name, sex);
    
    this.job=job;
}

//原型链  通过原型来继承父级的方法  这种赋值会影响Person的方法  不推荐使用
//Worker.prototype=Person.prototype;

//循环赋值 for(var i in Person.prototype) { Worker.prototype[i]=Person.prototype[i]; } Worker.prototype.showJob=function () { alert(this.job); }; var oP=new Person('blue', '男'); var oW=new Worker('blue', '男', 'php'); oP.showName(); oP.showSex(); oW.showName(); oW.showSex(); oW.showJob();

猜你喜欢

转载自www.cnblogs.com/yanyiyaner/p/9177544.html
今日推荐