一.原型
1.所有的引用类型(数组、对象、函数),都具有对象特性,都可以自由扩展属性。null除外。
2.所有的引用类型(数组、对象、函数),都有一个_proto_属性,属性值是一个普通的对象。_proto_的含义是隐式原型。
3.所有的函数(不包括数组、对象),都有一个prototype属性,属性值是一个普通的对象。prototype的含义是显式原型。(实例没有这个属性)
4.所有的引用类型(数组、对象、函数),_proto_属性指向它的构造函数的prototype值。
当试图获取一个对象的某个属性时,如果这个对象本身没有这个属性,那么会去它的_proto_中寻找(即它的构造函数的prototype)
function Foo(name) {
this.name = name;
}
Foo.prototype.alertName = function () {// 既然 Foo.prototype 是普通的对象,那也允许给它添加额外的属性 alertName
console.log(this.name);
}
var fn = new Foo('smyhvae');
fn.printName = function () {
console.log(this.name);
}
//测试
fn.printName(); //输出结果:smyhvae
fn.alertName(); //输出结果:smyhvae
虽然 alertName 不是 fn 自身的属性,但是会从它的构造函数的prototype里面找。
二.原型创建对象和方法
通过构造函数创建对象时,方法以及属性并不能进行共享,当定义声明的变量对象有多少,将创建多少个属性和方法,极大的损耗内存,效率极低
通过在原型上添加方法和属性,使之成为一个共享的属性和方法,因其在原型prototype上,故创建相同的类,都将拥有此方法火星合属性
将局部变量转换为全局变量
// 原理:将局部变量追加到全局window上,使之成为window上的属性或者方法
(function(win){
var num=10;
win.num=num;
}(window))
console.log(num);
三.实例----随机 小方块的实现
(function () {
function Random() {
}
//共享的方法:写在原型对象中
Random.prototype.getRandom = function (min, max) {
return parseInt(Math.random() * (max - min) + min);
}
//将随机数对象暴露给window成为全局对象
window.random = new Random();
}());
//2. 产生随机小方块
(function () {
//2.1 获取地图
var map = document.querySelector(".map");
//2.2 产生小方块---面向对象---宽,高,背景颜色,位置(x,y)
function Food(width, height, color) {
this.width = width || 20;
this.height = height || 20;
this.color = color || "pink";
//创建元素:createElement
this.element = document.createElement("div");
this.x = 0;//随机位置x
this.y = 0;//随机位置y
}
//2.3 初始化小方块的显示位置
Food.prototype.init = function () {
var dvObj = this.element;
//把小方块追加到map中
map.appendChild(dvObj);
// //小方块的位置是随机的,----脱离文档流
dvObj.style.position = "absolute";
dvObj.style.width = this.width + "px";
dvObj.style.height = this.height + "px";
dvObj.style.background = this.color;
//产生随机位置
this.render();
}
//2.4 产生随机位置
Food.prototype.render = function () {
var dvObj = this.element;
//获取随机坐标[0,33)
var x = random.getRandom(0, map.offsetWidth / this.width);
var y = random.getRandom(0, map.offsetHeight / this.height);
//设置left和top的值
this.x = x * this.width;
this.y = y * this.height;
dvObj.style.left = this.x + "px";
dvObj.style.top = this.y + "px";
}
window.Food = Food;//将对象暴露给window,成为全局对象
}());
var food = new Food();
food.init();