Премини към съдържанието
Форумът в приложение

По-лесно сърфиране. Научи повече.

Kaldata.com - Форуми

Приложение на форума на цял екран с push известия, значки и други.

За да инсталирате това приложение на iOS и iPadOS
  1. Докоснете Иконата за споделяне в Safari
  2. Превъртете менюто и докоснете Добавяне към началния екран.
  3. Докоснете Добавяне в горния десен ъгъл.
За да инсталирате това приложение на Android
  1. Докоснете менюто с 3 точки (⋮) в горния десен ъгъл на браузъра.
  2. Докоснете Добавяне към началния екран или Инсталиране на приложение.
  3. Потвърдете, като докоснете Инсталиране.

Добре дошли!

Добре дошли в нашите форуми, пълни с полезна информация. Имате проблем с компютъра или телефона си? Публикувайте нова тема и ще намерите решение на всичките си проблеми. Общувайте свободно и открийте безброй нови приятели.

Моля, регистрирайте се за да публикувате тема и да получите пълен достъп до всички функции.

 

JavaScript: Проблем с наследяване на свойство?

Featured Replies

Здравейте, имам проблем с наследяването на пропърти от главният клас, като идеята ми е да го направя по малко по-интелигентен начин без в конструктора на подкласа да правя същата декларация

this.x=arguments[0];
В момента винаги получава стойност undefined, въпреки че съм подал аргумент когато инстанцирам класа. Ето това ми е целият код:
<script type="text/javascript">

			function first() {

				this.x=arguments[0];

			}


			second.prototype=new first();

			second.prototype.constructor=second;


			function second() {

				first.call(this);

			}


			var a=new second(10);

			alert(a.x);

		</script>

Предварително благодаря на отзовалите се.

  • Автор

Ето го решението на проблема, знаех си че има семпло решение но но няма кой да чете :yanim:

function first(to) {

				this.x=to;

			}


			second.prototype=new first();

			second.prototype.constructor=second;


			function second(to) {

				this.base=first;

				this.base(to);

			}


			var a=new second(10);

			alert(a.x);

  • Автор

Появи се нов проблем и отново заради аргумент, този път в един метод на подкласа отново нямам достъп до аргумета, като тук не искам изцяло да предефинирам метода а просто искам да добавя функционалност към старата част на метода.

Ето подобен код в който отново не мога да извърша операцийте с аргумента който подавам.

function first() {

				this.x=10;

			}

			first.prototype.calculate=function (y) {

				this.x+=y;

			}


			second.prototype=new first();

			second.prototype.constructor=second;


			function second() {

				first.call(this);

			}

			second.prototype.calculate=function (y) {

				first.prototype.calculate.call(this);

				alert(this.x);

			}

			var a=new second();

				a.calculate(5);
Е не вече започвам да се ядосвам, толкова глупости само за няколко часа. На някой мод ако му се струва глупава темата нека я делне, то се е видяло че само глупости питам. Ето го решението все пак ако на някой му трябва.
function first() {

				this.x=10;

			}

			first.prototype.calculate=function (y) {

				this.x+=y;

			}


			second.prototype=new first();

			second.prototype.constructor=second;


			function second() {

				first.call(this);

			}

			second.prototype.calculate=function (y) {

				first.prototype.calculate.call(this,y);

				alert(this.x);

			}

			var a=new second();

				a.calculate(10);

  • Автор

Цялата врява беше заради този градиент, или по точно нещо като библиотека за създаване на градиенти с JavaScript.Всякакви критики относно кода и комуникацията между класовете са добре дошли cool.gif

Измених малко структурата, и добавих още един градиент, демото е доста тежичко.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

"http://www.w3.org/TR/html4/loose.dtd">

<html>

	<head>

		<title>New Document</title>

		<style type="text/css">

			html,body {

				margin: 0;

				padding: 0;

				height: 100%;

			}

			.left {

				float: left;

			}

			.right {

				float: right;

			}


			#first,#second,#three,#four,#five {

				width: 150px;

				height: 150px;

				overflow: hidden;

				float: left;

				margin-right: 10px;

				border: 1px solid black;

			}

		</style>

		<script type="text/javascript">

			Gradient.prototype.color=new Array();

			Gradient.prototype.steping=new Array();


			function Gradient(from,to,parents) {

				this.from=(from==null) ? 'ffffff' : from;

				this.to=(to==null) ? '000000' : to;

				this.parents=(parents==null) ? document.body : parents;

				this.step=100;

				this.wh=100/this.step;

			}


			Gradient.prototype.CreateObj=function (red,green,blue) {

				this.el=document.createElement('div');

				this.el.style.overflow='hidden';

				this.el.style.backgroundColor='rgb('+Math.round(red)+','+Math.round(green)+','+Math.round(blue)+')';

				this.el.style.height=this.wh+'%';

				this.parents.appendChild(this.el);

			}


			Gradient.prototype.Calculate=function () {

				var start=0;

				var end=2;

					for (i=0;i<3;i++, start+=2, end+=2) {

						this.color[i]=parseInt(this.from.substring(start,end),16);

						this.steping[i]=(this.color[i]-parseInt(this.to.substring(start,end),16))/this.step;

					}

			}

			Gradient.prototype.Decrement=function (sender) {

				for (n=0;n<sender.length;n++) {

					sender[n]-=this.steping[n];

				}

			}


			Gradient.prototype.CreateGradient=function () {

				this.Calculate();

				for (i=0;i<this.step;i++) {

					this.CreateObj(this.color[0],this.color[1],this.color[2]);

					this.Decrement(this.color);

				}

			}


			DiagonalGradient.prototype=new Gradient();

			DiagonalGradient.prototype.constructor=DiagonalGradient;


			function DiagonalGradient(from,to,parents) {

				Gradient.call(this,from,to,parents);

				this.step=50;

				this.dg_color=new Array();

				this.wh=(100/this.step)*2;

			}


			DiagonalGradient.prototype.CreateObj=function (red,green,blue) {

				Gradient.prototype.CreateObj.call(this,red,green,blue);

				this.el.style.width=this.wh+'%';

				this.el.className='left';

			}


			DiagonalGradient.prototype.CreateGradient=function () {

				this.Calculate();

				var length=this.step/2;

					for (i=0;i<length;i++) {

						for (x=0;x<this.color.length;x++) {

							this.dg_color[x]=this.color[x];

						}

						for (j=0;j<length;j++) {

							this.CreateObj(this.dg_color[0],this.dg_color[1],this.dg_color[2]);

							this.Decrement(this.dg_color);

						}

						this.Decrement(this.color);

					}

			}


			DiagonalRightLeft.prototype=new DiagonalGradient();

			DiagonalRightLeft.constructor=DiagonalRightLeft;


			function DiagonalRightLeft(from,to,parents) {

				DiagonalGradient.call(this,from,to,parents);

			}


			DiagonalRightLeft.prototype.CreateObj=function (red,green,blue) {

				DiagonalGradient.prototype.CreateObj.call(this,red,green,blue);

				this.el.className='right';

			}


			RombGradient.prototype=new DiagonalGradient();

			RombGradient.prototype.constructor=RombGradient;


			function RombGradient(from,to,parents) {

				DiagonalGradient.call(this,from,to,parents);

				this.step=30;

				this.wh=100/this.step;

			}


			RombGradient.prototype.Increment=function (sender) {

				for (m=0;m<sender.length;m++) {

					sender[m]+=this.steping[m];

				}

			}


			RombGradient.prototype.UpDown=function (num,arr) {

				if (num<this.step/2) {

					this.Decrement(arr);

				}

				else {

					this.Increment(arr);

				}

			}


			RombGradient.prototype.CreateGradient=function () {

				this.Calculate();

					for (i=0;i<this.step;i++) {

						for (x=0;x<this.color.length;x++) {

							this.dg_color[x]=this.color[x];

						}

						for (j=0;j<this.step;j++) {

							this.CreateObj(this.dg_color[0],this.dg_color[1],this.dg_color[2]);

							this.UpDown(j,this.dg_color);

						}

						this.UpDown(i,this.color);

					}

			}


			HorinzontalGradient.prototype=new Gradient();

			HorinzontalGradient.constructor=HorinzontalGradient;


			function HorinzontalGradient(from,to,parents) {

				Gradient.call(this,from,to,parents);

			}


			HorinzontalGradient.prototype.CreateObj=function (red,green,blue) {

				Gradient.prototype.CreateObj.call(this,red,green,blue);

				this.el.className='left';

				this.el.style.width=this.wh+'%';

				this.el.style.height=100+'%';

			}


			function Loader() {

				var first=new Gradient('000000','ffffff',document.getElementById('first'));

					first.CreateGradient();


				var second=new HorinzontalGradient('64D87E','ffffff',document.getElementById('second'));

					second.CreateGradient();


				var three=new DiagonalGradient('ff9900','ffffff',document.getElementById('three'));

					three.CreateGradient();


				var four=new DiagonalRightLeft('ffffff','ff0000',document.getElementById('four'));

					four.CreateGradient();


				var five=new RombGradient('153EE8','ffffff',document.getElementById('five'));

					five.CreateGradient();

			}

			window.onload=Loader;

		</script>

	</head>

	<body>	

		<div id="first"></div>

		<div id="second"></div>

		<div id="three"></div>

		<div id="four"></div>

		<div id="five"></div>

	</body>

</html>

Ето това е демото

Редактирано от abozhilov (преглед на промените)

Добавете отговор

Можете да публикувате отговор сега и да се регистрирате по-късно. Ако имате регистрация, влезте в профила си за да публикувате от него.

Гост
Публикацията ви съдържа термини, които не допускаме! Моля, редактирайте съдържанието си и премахнете подчертаните думи по-долу. Ако замените букви от думата със звездички или друго, за да заобиколите това предупреждение, профилът ви ще бъде блокиран и наказан!
Напишете отговор в тази тема...

Разглеждащи това в момента 0

  • Няма регистрирани потребители разглеждащи тази страница.

Дарение

  • Подкрепи съществуването на форума - направи дарение
    26%
    Дарени 256.00 EUR от нужните 1,000.00 EUR

Бюлетин

Получавайте известие, когато има важна промяна или новина свързана с форума.

Профил

Навигация

Търсене

Търсене

Конфигуриране на push известия в браузъра

Chrome (Android)
  1. Докоснете иконата на катинар до адресната лента.
  2. Докоснете Разрешения → Известия.
  3. Променете предпочитанията си.
Chrome (Desktop)
  1. Кликнете върху иконата на катинар в адресната лента.
  2. Изберете Настройки на сайта.
  3. Намерете Известия и коригирайте предпочитанията си.