自定义构造函数方式
function Person(name, age) {
this.name = name;
this.age = age;
this.walk = function () { console.log("walk"); };
}
通过prototype进行函数的声明
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.walk = function () { console.log("walk");};
var person1 = new Person("W1", 20);
var person2 = new Person("W2", 20);
person1.walk = person2.walk
此时函数在构造函数的 prototype 中
通过原型来添加的方法, 可以解决数据共享问题, 达到节省空间的目的.
在原型的函数中 this 指代实例对象.
Person.prototype.walk = function () { console.log("walk"); console.log(this);}
person1.walk() 调用时,其中的 this 指代的就是 person1 这个实例对象
function ChangeStyle(btnObj, divObj, newStyles){
this.btnObj = btnObj;
this.divObj = divObj;
this.newStyles= newStyles;
}
ChangeStyle.prototype.acting= function(){
var that = this;
this.btnObj.onclick = function(){
//如果在这个函数里面使用 this this 指代的是 this.btnObj
for(var key in that.newStyles){
that.divObj.style[key] = that.newStyles[key];
}
}
}
var newStyle = {"width":"500px", "height":"800px"};
var cs = new ChangeStyle(document.getElementById("btn"), document.getElementById("div"), newStyle);
cs.acting();
实例对象中有个属性 __proto__, 是对象, 原型,不是标准属性, 浏览器使用
构造函数中有一个属性 prototype, 也是对象, 是标准属性,
构造函数, 实例对象和原型对象之间的关系
1. 构造函数创建实例对象(实例化对象)
2. 构造函数的prototype指向原型对象
3. 原型对象的 constructor 构造器指向构造函数
4. 实例对象 __proto__属性 指向构造函数的原型对象
5. 构造函数的原型对象(prototype)中的方法是可以被实例对象直接访问的
简单的使用原型的方式
Person.prototype = {
constructor: Person, // 必须带有, 如果没有 则原来的constructor会被覆盖掉
height: "138",
weight: "55",
run: function(){console.log("running");}
}
此时 height, weight 和 run 都在 原型对象里面
原型中的方法
1. 实例对象的方法是可以相互调用的
2. 原型中的方法是可以相互访问的
实例对象使用属性和方法层层搜索
function Person(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
this.walk = function(){
console.log("walking");
}
}
Person.prototype.sex = "女";
Person.prototype.height = "188";
var person = new Person("W", 20, "男");
person.sex 仍然是 "男", 但是 person.height = "188";
实例对象中使用的属性或方法先在实例中查找, 如果没有则去实例对象的 __proto__ 原型指向的 原型对象 prototype 中找, 找到了则使用,没有则报错
为内置对象添加原型方法
添加后相当于给内置的源码进行修改
修改局部变量为全局变量
(function(win){
var num = 10;
win.num = num;
})(window);
console.log(window.num);
console.log(num);
把局部变量给window中的某个属性
通过自调用函数产生一个随机数对象, 在自调用函数外面调用该随机对象的方法产生随机数
(function (window){
function Random(){
}
Random.prototype.getRandom = function(){
return Math.floor(Math.random*5);
}
window.Random = Random;
})(window);
var random = new Random();
random.getRandom();