在函数原型上添加属性方法

代码、总结的参考来源

——选自《JavaScript高级程序设计(第3版)》.

// code block
	function person(){}; 
	var person1 = new person();

方法一

每个属性或方法直接添加到原型对象上。

// code block
	person.prototype.name = "Nicholas"; 
	person.prototype.age = 29; 
	person.prototype.job = "softWare Engineer"; 
	person.prototype.sayName = function(){
		console.log(this.name)
	};

用instanceof操作符测试Object、Person返回true,constructor属性正常指向person。

  1. Object.keys 方法,接受一个对象作为参数,返回一个包含所有可枚举属性的字符串数组。
  2. Object.getOwnPropertyNames 方法,接受一个对象作为参数,返回所有实例属性,无论它是否可枚举。
// code block
	var keys = Object.keys(person.prototype) ;
	console.log(keys) ;  // ["name", "age", "job", "sayName"]
	var getPropertys = Object.getOwnPropertyNames(person.prototype) ;
	console.log(getPropertys ) ;  // ["constructor", "name", "age", "job", "sayName"]
	console.log(person1 instanceof Object) ; //true
	console.log(person1 instanceof person) ; //true
	console.log(person1.constructor == person) ; //true
	console.log(person1.constructor == Object) ; //false

方法二

将原型对象设置为等于一个以对象字面量形式创建的新对象,该方法本质上重写了默认的prototype对象。

// code block
	person.prototype = {
		name: 'Nicolas', 
		age: 29,
		job: 'sofyWare Engineer', 
		sayName: function(){
			alert(this.name)
		}
	}

	var keys = Object.keys(person.prototype) ;
	console.log(keys) ;  // ["name", "age", "job", "sayName"]
	var getPropertys = Object.getOwnPropertyNames(person.prototype) ;
	console.log(getPropertys ) ;  // ["name", "age", "job", "sayName"]
	console.log(person1 instanceof Object) ; //true
	console.log(person1 instanceof person) ; //true
	console.log(person1.constructor == person) ; //false
	console.log(person1.constructor == Object) ; //true

这个方法有两个注意事项:

  1. 原型对象的constructor属性不再指向prototype属性所在函数,改为指向Object。
  2. 重设constructor属性指向prototype属性所在函数后,constructor属性的[[Enumerable]]特性设为了true。(默认情况下constructor属性不可枚举)

重设constructor属性为适当的值。

// code block
	person.prototype = {
		constructor: person,
		name: 'Nicolas', 
		age: 29,
		job: 'sofyWare Engineer', 
		sayName: function(){
			alert(this.name)
		}
	}

	var keys = Object.keys(person.prototype) ;
	console.log(keys) ;  // ["constructor", "name", "age", "job", "sayName"]
	var getPropertys = Object.getOwnPropertyNames(person.prototype) ;
	console.log(getPropertys ) ;  // ["constructor", "name", "age", "job", "sayName"]
	console.log(person1 instanceof Object) ; //true
	console.log(person1 instanceof person) ; //true
	console.log(person1.constructor == person) ; //true
	console.log(person1.constructor == Object) ; //false
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值