前端原型和原型链构造函数的使用

61 阅读1分钟

 

目录

前言

导语

代码部分

 总结

代码部分

 总结


前言

我是歌谣 歌谣的意志是永恒的 放弃很容易 但是坚持一定很酷

导语

前端原型和原型链构造函数的使用

​编辑

代码部分

function Father(name) {
				this.name = name
			}
			Father.prototype.dance = function () {
				console.log('I am dancing')
			}
			function Son(name, age) {
				Father.call(this, name)
				this.age = age
			}
			Son.prototype = Father.prototype
			//为子类添加方法
			Son.prototype.sing = function () {
				console.log('I am singing')
			}
			let son = new Son('小红', 100)
			//此时父类也被影响了
			console.log(Father.prototype,"father") //{dance: 
ƒ, sing: ƒ, constructor: ƒ}

 总结

利用Son.prototype = Father.prototype改变原型指向,但此时我们给子类增加原型方法,同样会影响到父类。

{dance:
ƒ, sing: ƒ, constructor: ƒ}

代码部分

	function Father(name) {
				this.name = name
			}
			Father.prototype.dance = function () {
				console.log('I am dancing')
			}
			function Son(name, age) {
				Father.call(this, name)
				this.age = age
			}
			Son.prototype = new Father()
			Son.prototype.sing = function () {
				console.log('I am singing')
			}
			let son = new Son('小红', 100)
			console.log(Father.prototype,"Father") //{dance: ƒ, 
constructor: ƒ}

 总结

子类的原型指向父类的实例,这样就可以顺着原型链共享父类的方法了。并且为子类添加原型方法的时候,不会影响父类。