首页 > 编程语言 > 详细

javascript基础

时间:2020-07-26 11:05:34      阅读:78      评论:0      收藏:0      [点我收藏+]

一、hasOwnProperty vs isPrototyOf

1&2互为补充

function siteAdmin(nickName,siteName){
 this.nickName=nickName;
 this.siteName=siteName;
}
siteAdmin.prototype.showAdmin = function() {
 alert(this.nickName+"是"+this.siteName+"的站长!")
};
siteAdmin.prototype.showSite = function(siteUrl) {
 this.siteUrl=siteUrl;
 return this.siteName+"的地址是"+this.siteUrl;
};

var matou=new siteAdmin("脚本之家","WEB前端开发");
var matou2=new siteAdmin("脚本之家","WEB前端开发");

1. hasOwnProperty: 对象求属性,但是不包括原型链里的。

alert(matou.hasOwnProperty("nickName"));//true
alert(matou.hasOwnProperty("age"));//true
alert(matou.hasOwnProperty("showAdmin"));//false
alert(matou.hasOwnProperty("siteUrl"));//false
alert(siteAdmin.prototype.hasOwnProperty("showAdmin"));//true
alert(siteAdmin.prototype.hasOwnProperty("siteUrl"));//false

2. isPropertyof对象是否继承与某个原型链。 判断某个原型链,该对象有没有继承。

alert(siteAdmin.prototype.isPrototypeOf(matou))//true

 

二、object.create (shadowcopy and 原型链继承) / object freeze 

 

 

const obj = {
  data: 1,
  compositor: {
    b: 2,
    c: {
      data: 2,
    },
  },
  m: undefined,
  get: () => {
    return this.xxx.data;
  },
};
const test1 = obj;
test1.data = 2;
console.log(obj); // { data: 1, compositor: { b: 2 }, get: [Function: get] }

console.log(JSON.parse(JSON.stringify(obj))); //!missing get { data: 1, compositor: { b: 2 } }
const test3 = { ...obj };
test3.compositor.b = 4;
console.log(obj);
console.log(test3);

const test = Object.create(obj); //!test的原型链继承了obj shalowcopy the property
test.__proto__.data = 3;
test.__proto__.compositor.b = 3;
console.log(test.__proto__); //!should be __proto__

//!test shadow
const objclone = {
  compositor: {
    data: {
      m: 3,
    },
  },
  get: () => {
    return this.xxx.m;
  },
};
const test33 = { ...objclone };
test33.compositor.data = 4;
console.log(objclone);
console.log(test33);

//! deepcopy success
const test34 = { ...objclone };
test34.compositor = { data: 6 };
console.log(objclone);
console.log(test34);

function deepcopy(obj1) {
  if (typeof obj1 != "object" || obj1 == null) return obj1;
  var newObj = obj1.constructor();
  console.log(newObj);
  for (let prop in obj1) {
    if (typeof obj1[prop] == "object") {
      newObj[prop] = deepcopy(obj1[prop]);
    } else {
      newObj[prop] = obj1[prop];
    }
  }
  return newObj;
}
function typeString(obj) {
  var cons = Object.prototype.toString.call(obj).slice(8, -1);

  return cons === "Array" || cons === "Object";
}
const testfinal = deepcopy(obj);
testfinal.compositor.c.data = 6;
console.log("deepcopy", deepcopy(obj));
console.log("deepcopy", deepcopy(testfinal));

 

javascript基础

原文:https://www.cnblogs.com/connie313/p/13379139.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!