Javascript 之Constructors and prototyping

这里介绍如何在javascript中使用Constructor 和prototyping:

constructor就是设计一个Object的蓝图,如下:
function macaw(name){
    this.name = name;
    this.say(){
        alert("我是金刚鹦鹉,我的名字叫:"+this.name);
    }
}
这样我们就可以使用new关键字来创建一个对象
     var noeMacaw = new macaw("snowflower");
而这个对象的属性和方法则通过constructor中的this绑定到了该对象上面,我们可以使用new来创建不同名称的macaw.

如果我们已经定义了一个macaw的structors,但还需要添加一些方法进去,则就可以使用prototyping了,如下:
macaw.prototype.getName = function(){
   return this.name
}
当然关于prototype,它也可以被用于prebuilt Object上面,比如Date,String等,使用起来的语法也为:
  String.prototype.xxx = function (...){}

你可能感兴趣的:(JavaScript,prototype)