天天看点

Js 原型初步认识

一个函数可以看成一个类,原型是所有类都有的一个属性,原型的作用就是给这个类的每一个对象都添加一个统一的方法
           
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>Document</title>
    <script>
    //声明一个类
    function Person(name,age)
    {
        this.name=name;
        this.age=age;
    }
    //使用原型给类添加方法
    Person.prototype.show=function()
    {
        alert("我叫"+this.name+",今年"+this.age);
    }
    //创建两个对象
    var person1 =new Person('张三',);
    var person2 =new Person('李四',);
    //调用原型里面的方法
    person1.show();
    person2.show();
    </script>
</head>
<body>

</body>
</html>
           

疑问

直接用Person.show=function(){alert(“”)} 那么下面两个person1和person2不也有show()这个方法吗

答曰:

这样写的话是不能person1.show()这样调用的,只能Person.show()这样调用,这个就像其他面向对象的语言中的类的静态方法那样。
           

继续阅读