Skip to content

原型链模式扩展-this #13

Open

Description

@Yangxiaqing

在原型模式中,this常用的有两种情况:

  • 在类中this.xxx=xxx; this--->当前类的实例
  • 某一个方法中的this---->看执行的时候"."前面是谁this就是谁
    • 需要先确定this的指向(this是谁)
    • 把this替换成对应的代码
    • 按照原型链查找的机制,一步步的查找结果
function Fn() {
	this.x = 100;
	this.y = 200;
	this.getY = function () {
		console.log(this.y);
	};
}
Fn.prototype = {
	constructor: Fn,
	y: 300,
	getX: function () {
		console.log(this.x);
	},
	getY: function () {
		console.log(this.y);
	}
};
var f = new Fn;
f.getX();//100
f.__proto__.getX();// --->this是f.__proto__--->console.log(f.__proto__.x) --->undefined

Fn.prototype.getX();//undefined
f.getY();//200
f.__proto__.getY();//300

在内置类的原型上扩展我们的方法:

数组去重:

Array.prototype.myUnique = function() {
	//this-->ary
	var obj = {};
	for(var i = 0;i < this.length; i++){
		var cur = this[i];
		if(obj[cur] == cur) {
			this[i] = this[this.length - 1];
			this.length--;
			i--;
			continue;
		}
		obj[cur] = cur;
	}
	obj = null;
}
var ary = [12,23,23,13,12,13,23];
ary.myUnique();
console.log(ary);
//Array.prototype.myUnique();//this--->Array.prototype

链式写法:执行完成数组的一个方法可以紧接着执行下一个方法

var ary = [12,23,23,13,12,13,23];

ary.sort(function (a,b) {
	return a - b;
}).reverse().pop();
  • 原理:
    ary为什么可以使用sort方法?
    因为sort是Array.prototype上的公有的方法,而数组ary是Array这个类的一个实例,所以ary可以使用sort方法--->数组才能使用我们Array原型上定义的属性和方法.
    sort执行完成的返回值是一个排序后的“数组”,
    reverse执行完成的返回值是一个数组,可以继续执行pop
    pop执行完成的返回值是被删除的那个元素,不是一个数组了,所以再执行push会报错
Array.prototype.myUnique = function() {
	//this-->ary
	var obj = {};
	for(var i = 0;i < this.length; i++){
		var cur = this[i];
		if(obj[cur] == cur) {
			this[i] = this[this.length - 1];
			this.length--;
			i--;
			continue;
		}
		obj[cur] = cur;
	}
	obj = null;
	return this;// 目的是为了实现链式写法
}
var ary = [12,23,23,13,12,13,23];

ary.myUnique().sort(function (a,b) {
	return a - b;
});
console.log(ary);

Activity

  1. added a commit that references this issue on Mar 5, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions