设为首页 加入收藏

TOP

对对象方法,类方法,原型方法的理解
2017-10-10 15:12:46 】 浏览:9987
Tags:对象 方法 原型 理解

 

function People(name)
{
  this.name=name;
  //对象方法
  this.Introduce=function(){
    alert("My name is "+this.name);
  }
}
//类方法
People.Run=function(){
  alert("I can run");
}
//原型方法
People.prototype.IntroduceChinese=function(){
  alert("我的名字是"+this.name);
}

 

//测试

var p1=new People("Windking");

p1.Introduce();

People.Run();

p1.Run(); //error p1没有Run()方法

p1.IntroduceChinese(); 

 

对象方法是可以继承的即父元素一份子元素也有一份,如果实例很多则很浪费内存空间

类方法不被继承只能类自身调用

原型方法可被继承但是他是一个引用类型,只有一份,即使有很多实例,但都是针指向prototype一个

 

prototype

 

 

function Person(name){
                this.name=name;
            }
            
            Person.prototype.share=[];
            
            Person.prototype.printName=function(){
                alert(this.name);
            }
            
            var person1=new Person('Byron');
            var person2=new Person('Frank');
            
            person1.share.push(1);
            person2.share.push(2);
            console.log(person2.share); //[1,2]

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇JavaScript数组常见操作 下一篇使用angular的HttpClient搭配rxjs

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目