普通函数与构造函数

1、普通函数

function normalFn(){
  console.log(this);  //window
  return "这是一个普通函数";
}
normalFn();

2、构造函数(构造函数建议首字母大写,与普通函数区分开)

function Animal(name){
  this.name= name;
}
Animal.prototype.sayName = function(){
  alert(this.name);  //狗
 console.log(this);  //Animal{name: "狗"}
}
var dog = new Animal("狗");
dog.sayName();

3、普通函数与构造函数的区别

(1)、调用方式:构造函数使用new关键字调用

使用new关键字调用发生了什么?

a、第一步,创建一个空对象。var dog={}

b、第二步,将构造函数Animal()中的this指向新创建的对象dog。

c、第三步,将dog的_proto_属性指向Animal函数的prototype,创建对象和原型间关系

d、第四步,执行构造函数Animal()内的代码。


(2)、this:普通函数不建议使用this,普通函数的this指向window,这样无意间就会为window添加了一些全局变量或函数

构造函数的this指向实例对象


(3)、返回值:构造函数默认返回this即新的实例对象。也可以用return语句返回,返回值会根据return的类型有所不同,

当构造函数里调用return时,分两种情况:

a、return的是五种简单数据类型:String,Number,Boolean,Null,Undefined。

这种情况下,忽视return值,依然返回this对象。

b、return的是Object

这种情况下,不再返回this对象,而是返回return语句的返回值


posted @ 2016-08-18 14:14  ning0_o  阅读(199)  评论(0编辑  收藏  举报